How to only change the text in a DOM element without replacing any child elements

前端 未结 7 1247
一个人的身影
一个人的身影 2021-01-17 17:58

Hi I have a simple html structure

Title text inner text

What I want is to replace only the te

相关标签:
7条回答
  • 2021-01-17 18:23
    const ChgBtn = document.querySelector('#change-title')
    const title = document.querySelector('#page-title')
    
    ChgBtn.addEventListener('click', (event) => {
      if (title.innerHTML === 'job') {
        title.innerHTML = 'better job'
        event.target.innerHTML = 'Change title back'
      }
      else if (title.innerHTML === 'better job') {
        title.innerHTML = 'job'
        event.target.innerHTML = 'Change Title'
      }
      else {
        console.error('Wrong')
      }
    })
    
    0 讨论(0)
  • 2021-01-17 18:24

    I found this question which might be useful.

    you can get the child element by doing this:

    var h1_elt = document.getElementById(h1_elt_id);
    var span = h1_elt.getElementsByTagName("span");
    

    You can then use the spans innerHTML as part of the h1 elements innerHTML, i.e.: h1_elt.innerHTML = "new text "+span.innerHTML+""

    The only thing you would need to change about your HTML is to give the h1 element an id attribute, then use that in place of h1_elt_id.

    0 讨论(0)
  • 2021-01-17 18:24

    The following will work.

    var h1 = document.getElementById("h1"),
        children = Array.prototype.slice.call(h1.children),
        newText = document.createTextNode("Hello. ");
    
    h1.innerHTML = "";
    h1.appendChild(newText);
    
    while(children) {
        h1.appendChild(children.shift());
    }
    

    http://jsfiddle.net/TFYmv/

    Basically what you're doing is taking a picture of all the children in a specific element, changing the element completely, then re-appending all the previous children back onto the parent element using the picture we took.

    0 讨论(0)
  • 2021-01-17 18:32

    Using jQuery.contents() you can replace the nodeValue similar to this:

    $("h1").contents()[0].nodeValue = "new text ";
    

    DEMO using jQuery.contents() to replace a text node


    0 讨论(0)
  • 2021-01-17 18:32

    This is gonna work without jquery:

    $title = documento.querySelector('your h1 element');
    $title.firstChild.nodeValue = 'New Title text';
    
    0 讨论(0)
  • 2021-01-17 18:40
    $("h1").each(function() {
        var textNode = document.createTextNode("new text");
        this.replaceChild(textNode, this.firstChild);
    });
    

    DEMO: http://jsfiddle.net/FvbJa/

    0 讨论(0)
提交回复
热议问题