Home > Software engineering >  All elments got selected instead of last in Jquery
All elments got selected instead of last in Jquery

Time:10-13

I am sharing over here a sample code, for which i ran into a problem. I am trying to select the last element, but when i execute this code, all the elements got selected. Any help in this regard is much appreciated.

$(document).ready(function() {
  $("ul li").addClass("highlight");
});
.highlight {
  background: yellow;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h2>Unordered List</h2>
<ul>
  <li>First list item</li>
  <li>Second list item</li>
  <li>Third list item</li>
  <li>Fourth list item</li>
</ul>
<hr>
<h2>Another Unordered List</h2>
<ul>
  <li>First list item</li>
  <li>Second list item</li>
  <li>Third list item</li>
  <li>Fourth list item</li>
</ul>

CodePudding user response:

you didn't mention anywhere, that the code have to select the last element, thatswhy the code returns with all the elements selected.

Please modify the code with the below code.

$(document).ready(function(){
    $("ul li").last().addClass("highlight");
});

CodePudding user response:

For every last <li> in each <ul> : $("ul li:last-child")

For only the last <li> in the whole document : $("ul li").last()

$("ul li:last-child").addClass("highlight");
.highlight {
  background: yellow;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h2>Unordered List</h2>
<ul>
  <li>First list item</li>
  <li>Second list item</li>
  <li>Third list item</li>
  <li>Fourth list item</li>
</ul>
<hr>
<h2>Another Unordered List</h2>
<ul>
  <li>First list item</li>
  <li>Second list item</li>
  <li>Third list item</li>
  <li>Fourth list item</li>
</ul>

  • Related