JQuery change inner text but preserve html

前端 未结 14 2690
名媛妹妹
名媛妹妹 2020-12-01 06:56

I would like to change the text of a HTML element but preserve the rest of the inner html with jQuery.

For instance:

Some         


        
相关标签:
14条回答
  • 2020-12-01 07:57

    An alternative way would be to use the contents() method as follows:

    Given

    <a href="link.html">Some text <img src="image.jpg" /></a>
    

    you can replace 'Some text' with jQuery

    var text = $('a').contents().first()[0].textContent;
    $('a').contents().first()[0].textContent = text.replace("Some text", "Other text");
    

    jsFiddle example here.

    The idea of contents() was inspired by this question, answered by user charlietfl.

    0 讨论(0)
  • 2020-12-01 08:00

    just use some plain js functionality:

    $('a')[0].firstChild.nodeValue = "New Text";

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