jQuery: exclude children from .text() [duplicate]

A micro-plugin:

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

…having this HTML:

<div id="test"><b>Hello</b><span> World</span>!!!</div>

will result in:

var text = $('#test').ignore("span").text(); // "Hello!!!"
var html = $('#test').ignore("span").html(); // "<b>Hello</b>!!!"

if you want it faster and you need only to exclude the immediate children… use .children( instead of .find(

Leave a Comment