Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery First Item for Each ID

I have two seperate lists and each of the list should add class active. Here is my HTML:

<ul id="list1">
    <li class="item">Object 1</li>
    <li class="item">Object 2</li>
    <li class="item">Object 3</li>
</ul>
<ul id="list2">
    <li class="item">Object 1</li>
    <li class="item">Object 2</li>
    <li class="item">Object 3</li>
</ul>

CSS

.active {
  color: red;
}

JavaSript

$(document).ready(function () {
        $("[id^='list'] .item").first().addClass("active");
});

As you can see only the #list1's first item getting the active class. How can i achive give the both list's first item active class.

Here is the fiddle: https://jsfiddle.net/iCromwell/rkvzhebd/1/

like image 278
Cromwell Avatar asked Dec 30 '16 08:12

Cromwell


People also ask

How to find first element in jQuery?

The :first selector selects the first element. Note: This selector can only select one single element. Use the :first-child selector to select more than one element (one for each parent). This is mostly used together with another selector to select the first element in a group (like in the example above).

What is each() in jQuery?

each(), which is used to iterate, exclusively, over a jQuery object. The $. each() function can be used to iterate over any collection, whether it is an object or an array. In the case of an array, the callback is passed an array index and a corresponding array value each time.

How to find first element of div in jQuery?

The first() method returns the first element of the selected elements.


1 Answers

Try looping over the parent, and then target first .item

$(document).ready(function () {
    $("[id^='list']").each(function(){
       $(this).find('.item').first().addClass("active");
    });
});

Fiddle

like image 93
Adam Azad Avatar answered Oct 03 '22 10:10

Adam Azad