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

后端 未结 5 1509
情话喂你
情话喂你 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 11:02

    1. Clone the element.
    2. Loop through all child nodes (backwards, to avoid conflicts):
      If the element has a tagName attribute, then it's an element: Remove the node.
    3. Use innerText to get the textual contents (with fallback to textContent, when innerText is not supported).

    Code:

    var elem = document.getElementById('theelement');
    elem = elem.cloneNode(true);
    for (var i=elem.childNodes.length-1; i>=0; i--) {
        if (elem.childNodes[i].tagName) elem.removeChild(elem.childNodes[i]);
    }
    var innerText = elem['innerText' in elem ? 'innerText' : 'textContent'];
    

提交回复
热议问题