jquery exclude some child nodes from .text()

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

The html structure looks like this

parent may contain text
child 1 may contain text
4条回答
  •  独厮守ぢ
    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:

    Get this Ignore this

    Get this paragraph

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

    will result in:

    Get this
    

    Get this paragraph

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

提交回复
热议问题