Genocide_Hoax
Genocide_Hoax

Reputation: 853

Better way to Find which element has a specific class from an array of elements

Suppose I have a List like the following

  <ul>
     <li id="slide-a" class="slide-li active-slide"><a href="#" >A</a></li>
     <li id="slide-b" class="slide-li"><a href="#" >B</a></li>
     <li id="slide-c" class="slide-li"><a href="#" >C</a></li                        
  </ul>

Now , using Jquery I wanna Find out which Element has the class 'active-class'. One way would to have a nested if statement something like this:

if($("#slide-a").hasClass('active-slide'))
{
  active = 'slide-a';
}
else
{
  if($("#slide-b").hasClass('active-slide'))
  {
    active = 'slide-b';
  }
  else
  {
    if($("#slide-c").hasClass('active-slide'))
    {
      active = 'slide-c';
    }
  }
}

My question is if there exists any way to optimize the code above. Is there a generic way to achieve this such that even if I add 10 more li's in the ul the code just works fine without any modification.

Upvotes: 1

Views: 130

Answers (3)

Kiran
Kiran

Reputation: 20313

Use Attribute starts with selector and .each(). Try this:

$(document).ready(function(){
    $('li[id^=slide]').each(function(){
        if($(this).hasClass('active-slide'))
            alert($(this).attr('id'));
    });
});

DEMO

If you have more than one li with classactive-slide use this:

$(document).ready(function(){
    var idVal = [];
    $('li[id^=slide]').each(function(){
        if($(this).hasClass('active-slide'))
            idVal.push($(this).attr('id'));
    });
    console.log(idVal);
});

DEMO

Upvotes: 3

SpoonIsBad
SpoonIsBad

Reputation: 187

You could a use jQuery $.each() on the ul to iterate through.

fiddle coming in a second.

Upvotes: 0

Farkhat Mikhalko
Farkhat Mikhalko

Reputation: 3655

Maybe just

var active = $(".active-slide").attr("id");

Demo

Upvotes: 6

Related Questions