python-coder
python-coder

Reputation: 2148

Get the element which has class active?

I've a list. I want to get the element of the id which has class active.

<ul class="nav nav-tabs" id="nav">
   <li class="active" id="day" onclick="changeDur('day')"><a data-toggle="tab">Day</a></li>
   <li id="week" onclick="changeDur('week')"><a data-toggle="tab">Week</a></li>
   <li id="month" onclick="changeDur('month')"><a data-toggle="tab">Month</a></li>
   <li id="year" onclick="changeDur('year')"><a data-toggle="tab">Year</a></li>
</ul>

Here's what I'm trying?

var period_val = $("#nav.active").attr('id');
alert(period_val)

It gives me undefined.

Where I'm going wrong?

Upvotes: 2

Views: 8112

Answers (3)

YemSalat
YemSalat

Reputation: 21486

var period_val = $("#nav .active").attr('id'); - needs a space after "#nav", otherwise you're looking for an UL which has id "nav" and class "active"

A child selector, as mentioned above would do as well.

Just to make my post a bit more usefull here are the links:

CSS selectors

Additional jQuery selectors

Upvotes: 4

hammus
hammus

Reputation: 2612

You can also use the child selector >:

   var period_val = $("#nav > .active").attr("id");

Upvotes: 2

ahren
ahren

Reputation: 16961

var period_val = $("#nav .active").attr('id');

You need a space to select descendent elements.

Upvotes: 8

Related Questions