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

前端 未结 7 1329
一个人的身影
一个人的身影 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: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.

提交回复
热议问题