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

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

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

**text to change** text t
14条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-22 08:05

    2019 vesrsion - Short & Simple

    document.querySelector('#your-div-id').childNodes[0].nodeValue = 'new text';
    

    Explanation

    document.querySelector('#your-div-id') is used for selecting the parent (the element which text you are about to change)

    .childNodes[0] selects the text node

    .nodeValue = 'new text' sets text node value to "new text"


    This answer is possibly inspired by Dean Martin's comment. Can't say for sure since I've been using this solution for years now. Just thought I should post this probability here because some people care about it more than the fact that this is the best solution.

提交回复
热议问题