Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve text from list tag but don't calculate the child tag [duplicate]

I'm trying to retrieve the calculation of the text within <li> but I don't need the child tag <p> to be considered in this calculation. So when I add the following it will naturally calculate all the text within <li>.

$('ul li').text().length;

From HTML:

<ul>
    <li>Count me<p>Don't count me please.</p></li>
</ul>

What are the possible ways to achieve this so the child tags text is not calculated?

like image 611
Nima Avatar asked Jan 19 '15 13:01

Nima


1 Answers

You can clone the element, remove the children and then extract the text:

var li = $('ul li').clone();
li.children().remove();
console.log(li.text().length);

This will work regardless of the number or type of child elements.

like image 67
Konstantin Dinev Avatar answered Oct 27 '22 20:10

Konstantin Dinev