get text of an element without children in javascript

后端 未结 4 589
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-17 18:47

How do I get the text of an element without the children? Neither element.textContent nor element.innerText seem to be working.

HTML:

4条回答
  •  感动是毒
    2020-12-17 19:36

    Just find the text nodes:

    var element = document.getElementById('whatever'), text = '';
    for (var i = 0; i < element.childNodes.length; ++i)
      if (element.childNodes[i].nodeType === Node.TEXT_NODE)
        text += element.childNodes[i].textContent;
    

    edit — if you want the text in descendant ("children") nodes, and (as is now apparent) you're using jQuery:

    $.fn.allText = function() {
      var text = '';
      this.each(function() {
        $(this).contents().each(function() {
          if (this.nodeType == Node.TEXT_NODE)
            text += this.textContent;
          else if (this.nodeType == Node.ELEMENT_NODE)
            text += $(this).allText();
        });
      });
      return text;
    };
    

    Hold on and I'll test that out :-) (seems to work)

提交回复
热议问题