'Set first child element to li with active state

I need to set the first-child parameter "always" to the <li> with the active class into a <ul> <li> structure.

Any help?



Solution 1:[1]

The following code snippet will add the active class to the clicked list item, reorder the list so it becomes the first child of its parent, and remove the active class from its siblings:

$("ul").on("click", "li", function() {
    var $this = $(this);
    $this.addClass("active")
         .prependTo($this.parent())
         .siblings().removeClass("active");
});

Solution 2:[2]

Do you mean:


$("ul li:eq(1)").addClass("active");

Solution 3:[3]

Are you trying to get a reference to the first li in the ul?

var li = $("ul li:first");

Are you trying get a reference to the li with class="active"?

var li = $("ul li.active");

Once you have the reference you need, you can set attributes or innerHTML:

$(li).attr("class", "active");
$(li).addClass("active");
$(li).text("abc");

Solution 4:[4]

Try this

<ul id="special">
  <li>Coffee</li>
  <li>Tea</li>
  <li>Milk</li>
</ul> 


$(document).ready(function()
{
 $("#special li:eq(0)").addClass("active");
})

Check this in fiddle http://jsfiddle.net/UsvRs/

Solution 5:[5]

<ul>
    <li>list item 1</li>
    <li>list item 2</li>
    <li>list item 3</li>
    <li>list item 4</li>
    <li>list item 5</li>
  </ul>

if above is your ul li structure you can use below script.

$(document).ready(function()
{
 $('li').eq(0).addClass("active");
});

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Frédéric Hamidi
Solution 2 Sudhir Bastakoti
Solution 3 Tony R
Solution 4 Akhil Thayyil
Solution 5 Ravichandran Jothi