Getting the last child of each parent using jQuery

Is there an easy way to select the last li of each of these lists using jQuery?

<ul> <li>1</li> <li>2</li> <li>3</li> </ul> <ul> <li>1</li> <li>2</li> <li>3</li> <li>4</li> </ul> <ul> <li>1</li> <li>2</li> </ul> 

I tried these two methods, but both of them return only one element.

 $("ul li").last() $("ul li:last") 

I would use the CSS: last-child pseudo-class, but since it was introduced in CSS3 and IE8 does not support it, I cannot

+6
source share
3 answers

I would use the CSS: last-child pseudo-class, but since it was introduced in CSS3 and IE8 does not support it, I cannot

You can use jQuery to select your elements, since jQuery implements it itself, so browsers that do not support it in CSS can still use it:

 $("ul li:last-child") 
+5
source

The :last-child selector is what you need. The same logic as the CSS3 :last-child selector, but you can freely use it in jQuery, since jQuery will provide it to you, even if the browser CSS mechanism does not understand it.

 $("ul li:last-child") 

From the documentation:

While :last matches only one element :last-child can match more than one: one for each parent.

Nice little demo

+5
source

Decision:

 $(document).ready(function() { $('ul li:last-child').css("color","red"); }); 

Check this script: http://jsfiddle.net/ganeshprabhu1994/surve/2/

+1
source

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


All Articles