How to get the text of the link in which there are children?

I am currently trying to figure out how to get the text of a link in which there are children. My html looks something like this:

<a href=""> The text I want to get <span> something I don't want to get </span> </a> 

I want to get only the "Text I want to get", and not include text for children.
Is there an easy way to do this?

+4
source share
3 answers
 $("#mylink").clone() .children() .remove() .end() .text() 

Find an example here :

+4
source

You can use contents to get all children, including text nodes. Then filter to just get text nodes.

 var $textNodes = $("a").contents() .filter(function(){ return this.nodeType == 3 }) var text = $textNodes.text(); 

http://jsfiddle.net/Cnhxe/

+3
source

I am not sure if the question provides enough information for all the features of tags and placement of children, but if the structure is always the same as the supplied item, you can do the following with jQuery:

 var linkText = $("a").text(); linkText = linkText.replace($("a span").text(), ""); alert(linkText); 

0
source

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


All Articles