addClass Jquery li

I'm a total newbie. I'm trying to add a class whenever a certain "li" is clicked. So far, it's not working for me. Here's some of the code that I have:

    <ul>
        <li id="a">A) Lucy</li>
        <li id="b">B) Bonnie</li>
        <li id="c">C) Sheila</li>
        <li id="d">D) Kai</li>
    </ul>

This is the Jquery that I'm using to try to add a class to it.

      $( "ul li #a" ).click(function() {
        $(this).addClass('correct');
      });

Answers 1

  • You were close-- you simply had a space between the selector and the id:

    • li#a means "an li with an id of 'a'"

    • li #a means "some element with an id of 'a' that's inside of an li".

    $( "ul li#a" ).click(function() {
       $(this).addClass('correct');
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <ul>
        <li id="a">A) Lucy</li>
        <li id="b">B) Bonnie</li>
        <li id="c">C) Sheila</li>
        <li id="d">D) Kai</li>
    </ul>


Related Articles