Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery getting values inside a ul li tag, but don't want a certain tag

Tags:

jquery

text

ajax

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!

like image 700
hellomello Avatar asked Jun 08 '12 05:06

hellomello


2 Answers

$("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/

like image 151
U.P Avatar answered Oct 08 '22 12:10

U.P


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/

like image 22
Sampson Avatar answered Oct 08 '22 13:10

Sampson