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

后端 未结 5 1505
情话喂你
情话喂你 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:39

    If you don't want to ignore the child element's inner text, use the following function:

    function getInnerText(el) {
        var x = [];
        var child = el.firstChild;
        while (child) {
            if (child.nodeType == 3) {
                x.push(child.nodeValue);
            }
            else if (child.nodeType == 1) {
                var ii = getInnerText(child);
                if (ii.length > 0) x.push(ii);
            }
            child = child.nextSibling;
        }
        return x.join(" ");
    }
    

提交回复
热议问题