parkwebdev
parkwebdev

Reputation: 33

How can I know which element has a class?

My page has six div elements.

Using jQuery and Z-Index, clicking on a button increases the width of one div to cover all the others. In the process, it also assumes the class: active (z-index:900).

When I click another button, the div with the class active should return to its original size and position. The original values are saved into variables, but how can I know the name of the element with the active class?

Upvotes: 1

Views: 76

Answers (3)

El Ronnoco
El Ronnoco

Reputation: 11922

$('.active')[0].id Will get you ID of first element having class of 'active'

Upvotes: 1

Michael Slade
Michael Slade

Reputation: 13877

This is one of the fundamental features of the jQuery function aka $().

Doing this:

var elements = $(".myclass");

will give you all of the elements that are using CSS class myclass. From there you can do this:

elements.css({
    left: orig_left,
    top: orig_top,
    width: orig_width,
    height: orig_height
});

The style changes will apply to all of the elements at once.

However if you wish to restore an element to its defaults (ie what was in the original html), you can do this:

elements.css({
    left: null,
    top: null,
    width: null,
    height: null
});

or even:

elements.attr("style","");

Upvotes: 3

Niclas Sahlin
Niclas Sahlin

Reputation: 1137

You can select all elements with the class: $('.youClass').

Upvotes: 0

Related Questions