How can I change an element's text without changing its child elements?

前端 未结 14 2089
难免孤独
难免孤独 2020-11-22 07:30

I\'d like to update element\'s text dynamically:

**text to change** text t
14条回答
  •  既然无缘
    2020-11-22 08:13

    Mark’s got a better solution using jQuery, but you might be able to do this in regular JavaScript too.

    In Javascript, the childNodes property gives you all the child nodes of an element, including text nodes.

    So, if you knew the text you wanted to change was always going to be the first thing in the element, then given e.g. this HTML:

    **text to change**

    text that should not change

    text that should not change

    You could do this:

    var your_div = document.getElementById('your_div');
    
    var text_to_change = your_div.childNodes[0];
    
    text_to_change.nodeValue = 'new text';
    

    Of course, you can still use jQuery to select the

    in the first place (i.e. var your_div = $('your_div').get(0);).

提交回复
热议问题