Is there a way to get innerText of only the top element (and ignore the child element's innerText)?

后端 未结 5 1496
情话喂你
情话喂你 2020-12-06 10:05

Is there a way to get innerText of only the top element (and ignore the child element\'s innerText) ?

Example:

top node text <
5条回答
  •  春和景丽
    2020-12-06 10:55

    This will work in your example: document.getElementById("item").firstChild.nodeValue;

    Note: Keep in mind that this will work if you know you are dealing with that specific HTML. If your HTML can change, for example to:

    child node text
    top node text

    then you should use the more generic solution by @Tim Down


    Here is working code snippet:

    window.onload = function() {
       var text = document.getElementById("item").firstChild.nodeValue;
       document.getElementById("result").innerText = text.trim();
    };
    #result {
      border: 1px solid red;
    }
    top node text
    child node text
    Result:

提交回复
热议问题