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

Given this HTML:

<a href="#" class="artist">Soulive<span class="create-play">Play</span></a>

I want to get the text content of the a (which is this in the context of my function) without the text content of the span, so I'm left with:

Soulive

If I do:

$(this).text();

I get:

SoulivePlay

How do I exclude the text content of the span?


Solution 1:

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(

Solution 2:

http://jsfiddle.net/r8kNL/

$(this).contents().filter(function() {
  return this.nodeType == 3;
}).text()

Solution 3:

$(this).clone().find('span').remove().end().text();

otherwise, with a different approach, if you're sure that your span elements always contain the word "play" at the end, just use a replace() or a substring() function, e.g.

var text = $(this).text();
text = text.substring(0, text.length-4);

the latter example is a too-localized and not bulletproof method for sure, but I mentioned just to propose a solution from a different point of view

Solution 4:

$( this.childNodes ).map( function(){
    return this.nodeType === 3 && this.nodeValue || "";
}).get().join("");