jQuery: exclude children from .text()

JavascriptJquery

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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 - Javascript

http://jsfiddle.net/r8kNL/

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

Solution 3 - Javascript

$(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 - Javascript

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiondaGUYView Question on Stackoverflow
Solution 1 - JavascriptRoko C. BuljanView Answer on Stackoverflow
Solution 2 - JavascriptRomanView Answer on Stackoverflow
Solution 3 - JavascriptFabrizio CalderanView Answer on Stackoverflow
Solution 4 - JavascriptEsailijaView Answer on Stackoverflow