Question

I have the following HTML content

<div>
  <ul>
    <li>USA</li>
    <li>UK</li>
    <li>France</li>
    <li>Russia</li>
    <li>Belgium</li>
    <li>India</li>
  </ul>
</div>

<input id="btnHighlight" type="button" value="Highlight"/>

When the user clicks the Highlight button, the program should change the colour of a particular list item, let's say the third list item to blue colour.

I know that every list item has its own unique index. But how can I access it directly using jQuery?

1 Answers

To select the third li element, do this:

$("li").eq(2)

The eq accepts an index that identifies the position of an element in a set and it selects the element corresponding to that index number. The first element will have the index number 0, and so on.

<script>
  $(document).ready(function() {
    $("#btnHighlight").click(function() {
      $("li").eq(2).addClass("highlighted");
    });
  });
</script>

<style>
  .highlighted { color:blue; }
</style>