rupali317
rupali317

Reputation: 512

Why jQuery's last() is not working on the last occurrence of an HTML element?

Overview:

In the following code, I am supposed to highlight the last occurrence of an html element with id = "sample" i.e. "This is the last paragraph". However, "This is the first paragraph" gets highlighted instead.

Questions:

1) Why is $("#sample:last").css("background-color", "yellow") not highlighting the last paragraph?

2) When I change to $("p#sample:last").css("background-color", "yellow"), then the last paragraph gets highlighted. Why does this work and not the scenario in question 1?

  <!DOCTYPE html>
  <html>
    <head>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
      <script>
        $(document).ready(function(){
            $("#sample:last").css("background-color", "yellow");
        });
      </script>
    </head>
    <body>

      <p id="sample">This is the first paragraph.</p>
      <p id="sample">This is the second paragraph.</p>
      <p id="sample">This is the last paragraph.</p>

    </body>
  </html>

Upvotes: 0

Views: 2194

Answers (2)

Hanif
Hanif

Reputation: 3795

Because of you using duplicate ID's. Valid markup dose not allow duplicate ID. Id should be unique in a single DOM structure that's why there no :last pseudo class available for ID selector. You should use class instead ID in this case.

Upvotes: 2

Wouter Bouwman
Wouter Bouwman

Reputation: 1013

The problem is that you're using id's instead of a class. You can only use an id once. The proper way of doing is this is to give them all the same class and to use the class selector . combined with :last.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>

<script>
  $(document).ready(function() {
    $(".sample:last").css("background-color", "yellow");
  });

</script>



<p class="sample">This is the first paragraph.</p>
<p class="sample">This is the second paragraph.</p>
<p class="sample">This is the last paragraph.</p>

http://jsfiddle.net/gt4L7zt2/

Upvotes: 5

Related Questions