简体   繁体   中英

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?

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

您需要一个空间来选择后代元素。

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

您还可以使用子选择器 >

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM