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!
$("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/
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/
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With