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

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

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

**text to change** text t
14条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 08:01

    For the specific case you mentioned:

    **text to change** text that should not change text that should not change

    ... this is very easy:

    var div = document.getElementById("foo");
    div.firstChild.data = "New text";
    

    You don't state how you want to generalize this. If, say, you want to change the text of the first text node within the

    , you could do something like this:

    var child = div.firstChild;
    while (child) {
        if (child.nodeType == 3) {
            child.data = "New text";
            break;
        }
        child = child.nextSibling;
    }
    

提交回复
热议问题