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

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

    function getDirectInnerText(element) {
      var childNodes = element.childNodes;
      result = '';
    
      for (var i = 0; i < childNodes.length; i++) {
        if(childNodes[i].nodeType == 3) {
          result += childNodes[i].data;
        }
      }
    
      return result;
    }
    
    element = document.querySelector("div#element");
    console.log(getDirectInnerText(element))
    top node text
    child node text

提交回复
热议问题