Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 877
daGUY Avatar asked Jul 05 '12 15:07

daGUY


2 Answers

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(

like image 54
Roko C. Buljan Avatar answered Sep 17 '22 17:09

Roko C. Buljan


http://jsfiddle.net/r8kNL/

$(this).contents().filter(function() {   return this.nodeType == 3; }).text() 
like image 38
Roman Avatar answered Sep 18 '22 17:09

Roman