jquery exclude some child nodes from .text()

前端 未结 4 1074
醉话见心
醉话见心 2020-12-18 22:19

The html structure looks like this

parent may contain text
child 1 may contain text
相关标签:
4条回答
  • 2020-12-18 22:48

    You can achieve that by cloning your node, removing the script tags and retrieving the text() value:

    var content = $('#parent').clone();
    content.find('script').remove();
    console.log(content.text());
    

    DEMO

    You should clone the node in order to asure an unchanged DOM tree afterwards.

    0 讨论(0)
  • 2020-12-18 22:53

    Try this:

    ($('#parent').text()).replace($('#parent script').text(),'');
    

    Check out this Fiddle.

    0 讨论(0)
  • 2020-12-18 22:56

    This works for me and seems very generic [EDITED to make the procedure clearer]

    var t = [];
    $("#parent").each(function(i,e) 
        {if (e.nodeName!="SCRIPT") t.push(e.innerText);}​);​​​​​​​​​​​​​​
    console.log(t);
    

    Instead of console.log() you should obviously collect the strings in some other way (array?) to use them in your code.

    http://jsfiddle.net/8eu4W/3/

    0 讨论(0)
  • 2020-12-18 23:08

    A nice small jQuery plugin: jQuery.ignore()

    $.fn.ignore = function(sel){
      return this.clone().find(sel||">*").remove().end();
    };
    

    Use like:

    $("#parent").ignore()                  // Will ignore all children elements
    $("#parent").ignore("script")          // Will ignore a specific element
    $("#parent").ignore("h1, p, .ignore")  // Will ignore specific elements
    

    Example:

    <div id="parent">
       Get this
       <span>Ignore this</span>
       <p>Get this paragraph</p>
       <div class="footer">Ignore this</div>
    </div>
    

    var ignoreSpanAndFooter = $("#parent").ignore("span, .footer").html();
    

    will result in:

    Get this
    <p>Get this paragraph</p>
    

    Snippet from this Answer: https://stackoverflow.com/a/11348383/383904

    0 讨论(0)
提交回复
热议问题