Jquery gets values ​​inside ul li tag but doesn’t want a specific tag

I am trying to get a 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 the tag as such

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

but also fixes x from a . How to remove a tag? There must be a simple solution that I am not familiar with

Thanks!

+6
source share
4 answers
 $("ul li").contents(':not(.close)').text() 

children () does not return text nodes; for all children, including text and node comments, use .contents () http://api.jquery.com/children/

+6
source

Pseudo-class custom filter

Write your own expression to capture text fields:

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

Result in the following compilation:

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

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

Custom method

You can 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 leads to the same conclusion that we see above.

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

+2
source

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

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

Now you can choose a more convenient version from the information: How to select text nodes using jQuery?

 $('ul li').contents().filter(function() { return this.nodeType == 3; }).text() 
+1
source
 $('ul li') .contents() // target to contents of li .filter(function() { return this.nodeType == 3; // filtering over textnode }).text(); // get the text value 

Demo

0
source

Source: https://habr.com/ru/post/917580/


All Articles