EdwardBlack EdwardBlack - 5 months ago 9
jQuery Question

How to select last element with last() without going through sub elements

I try to change the

background-color
attribute of the last
li
in my
ul
with id list1 (the li after "list item 4"). However, if i run
$( "ul#list1 li" ).last().css( "background-color", "red" );
then the function is selecting the very last
li
, which is list2 item1.

Is there a way to tell the function to not run through sub elements?




$( "ul#list1 li" ).last().css( "background-color", "red" );

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="list1">
<li>list1 item 1</li>
<li>list1 item 2</li>
<li>list1 item 3</li>
<li>list1 item 4</li>
<li>
<ul>
<li>list2 item 1</li>
</ul>
</li>
</ul>




Answer

Use .children() method which traverses only direct children.

	
$( "ul#list1").children().last().css( "background-color", "red" );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="list1">
  <li>list1 item 1</li>
  <li>list1 item 2</li>
  <li>list1 item 3</li>
  <li>list1 item 4</li>
  <li>
      <ul>
        <li>list2 item 1</li>
      </ul>
  </li>
</ul>