Mamadou
Mamadou

Reputation: 2307

Add class in html tag with jquery

I got this html code:

<form id = "xxx">
   <ul>
     <li class = "req" > </li>
     <li class = "req" > </li>
     <li class = "req" > </li>
     <li > </li>    ==================> HOW CAN I ADD A CLASS="req" to this li with jquery
     <li class = "req" > </li>
     ....
    <li class = "req" > </li>
  </ul>
</form>

So I rewrite the question: There is one li tag that has not ( class= "req"), how can i add that with jquery? Thank you

Upvotes: 3

Views: 5248

Answers (3)

Magnar
Magnar

Reputation: 28810

$("#xxx li").addClass("req");

is sufficient.

If you want to explicitly add it to only the li without req, you can do:

$("#xxx li:not(.req)").addClass("req");

If you want to only add the class to the fourth element, you would do:

$("#xxx li:eq(3)").addClass("req");

The 3 is because it uses a zero-based index for the elements.

Upvotes: 4

Tim
Tim

Reputation: 9489

With not you can check if an item has a certain attr.

$("ul#yourid").not(".req").addClas("req");

Upvotes: 1

Randy the Dev
Randy the Dev

Reputation: 26690

jQuery('li').addClass('req');

Upvotes: 0

Related Questions