6

I'm trying to get text value inside an li tag, but it has another tag that I don't want

example:

<ul>
<li><a class="close">x</a>text</li>
<li><a class="close">x</a>more text</li>
<li><a class="close">x</a>wohoooo more text</li>
</ul>

I can get tag like so

$("ul li").text();

but it also captures x from a. How do I remove the a tag? There's gotta be a simple solution that I'm not familiar with,

Thanks!

hellomello
  • 8,219
  • 39
  • 151
  • 297

4 Answers4

6
$("ul li").contents(':not(.close)').text()

children() does not return text nodes; to get all children including text and comment nodes, use .contents() http://api.jquery.com/children/

U.P
  • 7,357
  • 7
  • 39
  • 61
2

Custom Pseudo-Class Filter

Write your own expression for grabbing textnodes:

$.extend( $.expr[":"], {
    textnodes: function( e ) {
        return e.nodeType === 3;
    }
});

$("ul li").contents(":textnodes");

Resulting in the following collection:

["text","more text","wohoooo more text"]

Fiddle: http://jsfiddle.net/jonathansampson/T3MQc/

Custom Method

You could also extend jQuery.fn to provide your own method:

$.extend( $.fn, {
    textnodes: function() {
        return $(this).contents().filter(function(){
            return this.nodeType === 3;
        });
    }
});

$("ul li").textnodes();

This results in the same output we see above.

Fiddle: http://jsfiddle.net/jonathansampson/T3MQc/1/

Community
  • 1
  • 1
Sampson
  • 265,109
  • 74
  • 539
  • 565
1

This is pretty ugly, but it works. It clones the node, then removes all children and finally prints the text that's left:

$('ul li').clone()
  .children()
    .remove()
    .end()
  .text()

Managed to pull a nicer version from information fond here: How do I select text nodes with jQuery?

$('ul li').contents().filter(function() {
    return this.nodeType == 3;
}).text()
Community
  • 1
  • 1
Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
0
$('ul li')
   .contents()   // target to contents of li
   .filter(function() {    
      return this.nodeType == 3;  // filtering over textnode
}).text();  // get the text value

DEMO

thecodeparadox
  • 86,271
  • 21
  • 138
  • 164