JQuery InnerText not including sub element

前端 未结 4 1761
Happy的楠姐
Happy的楠姐 2020-12-03 23:39

Im wondering how I would get the text of a nested list item without getting the text of its children i.e.

  • I want t
4条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-03 23:49

    The following will get you a concatenated string of all the text nodes that are direct children of a node:

    function getChildText(node) {
      var text = "";
      for (var child = node.firstChild; !!child; child = child.nextSibling) {
        if (child.nodeType === 3) {
          text += child.nodeValue;
        }
      }
      return text;
    }
    
    alert( getChildText(document.getElementById("node")) );
    

提交回复
热议问题