get text of an element without children in javascript

后端 未结 4 582
爱一瞬间的悲伤
爱一瞬间的悲伤 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:27

    The text of an element is also a separate node. Consider this piece of code:

    <span>
        Some text
        <span>Inner text</span>
        More text
        <span>More inner text</span>
        Even more text
    </span>
    

    What do you mean now when you say you want the text of the element? Just the direct children?

    Then this piece code of code may help:

    for (var element in elements) {
        if (element.nodeType == Node.TEXT_NODE) {
            // do something
        }
    }
    
    0 讨论(0)
  • 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)

    0 讨论(0)
  • 2020-12-17 19:38

    In addition to answers like Pointy, handling newline character for <br/> can be done like this:

    txt = '';
    for (var i = 0; i < element.childNodes.length; ++i)
        if (element.childNodes[i].nodeType == 3) {
            txt += element.childNodes[i].textContent;
        } else if (element.childNodes[i].nodeType == 1) {
            name = element.childNodes[i].nodeName || element.childNodes[i].tagName || '';
            if (name.toUpperCase() == 'BR') {
                txt += '\n';
            }
        }
    return txt;
    
    0 讨论(0)
  • 2020-12-17 19:42

    This code achieves the same result as the two other answers, but in a more expressive, functional way. The filter and map array methods are supported in all modern browsers (IE9 and up).

    Throwing this in there since the other answers are a bit dated by now.

    var content = Array.prototype.filter.call(element.childNodes, function (element) {
        return element.nodeType === Node.TEXT_NODE;
    }).map(function (element) {
        return element.textContent;
    }).join("");
    
    0 讨论(0)
提交回复
热议问题