user1400191
user1400191

Reputation: 169

how do i get an id of an element which has a class

Let's say i have list

<ul id="left-side-menu" style="display: block;">

    <li> <a id="1" class="lists active" href="javascript:void(0)">My company 1</a></li>

    <li> <a id="2" class="lists" href="javascript:void(0)">My company 2</a></li>

    <li> <a id="3" class="lists" href="javascript:void(0)">My company 3</a></li>
</ul>

In order to get the id of an element which has active class using the lists class, i wrote like this

$("a.lists").hasClass("active").attr('id');

but it gives an error

$("a.lists").hasClass("active").attr is not a function

Please help me

Upvotes: 1

Views: 4190

Answers (3)

DQM
DQM

Reputation: 552

$("a.lists.active").attr('id');

Upvotes: 2

nnnnnn
nnnnnn

Reputation: 150010

The return value of the .hasClass() method is a boolean, and of course a boolean doesn't have an .attr() method.

To select an element that has multiple classes just list all of the required classes with no spaces between the names, like this:

$("a.lists.active").attr('id');

That should return the value of the id of the first element to match that selector, or undefined if no elements match. (If you expect to always have exactly one element with the "active" class it will be fine.)

Upvotes: 1

xdazz
xdazz

Reputation: 160833

$("a.lists.active").attr('id')

Upvotes: 7

Related Questions