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

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

    Just iterate over the child nodes and concatenate text nodes:

    var el = document.getElementById("your_element_id"),
        child = el.firstChild,
        texts = [];
    
    while (child) {
        if (child.nodeType == 3) {
            texts.push(child.data);
        }
        child = child.nextSibling;
    }
    
    var text = texts.join("");
    

提交回复
热议问题