SuperLuigi
SuperLuigi

Reputation: 299

How to change multiple div classes at once?

I have 2 li's that are clickable. On mouse click, I would like to change the class of 10 other divs on the page (not any of the divs being clicked on).

Here is the interaction I'm looking for:

-Clicking the first li sets the class of 10 divs to "class1". (these classes are already set by default)

-Clicking the second li changes the same 10 classes to "class2"

-Toggle back and fourth

How is this done?

Upvotes: 0

Views: 1860

Answers (3)

DwB
DwB

Reputation: 38300

Here is a fiddle

Upvotes: 1

Dutchie432
Dutchie432

Reputation: 29160

the answer provided by Wojciech is good and will work. But what if you want to add 100 clickable items? I prefer a methodology that is more expandable and generalized for broader use (not to mention more compact in size).

Alterative #1

you could use the jQuery index() function to find out the index of the clicked item and then apply the class that way...

$('li').click(function(){
    var index = $('li').index($(this))+1;
    $("div").setClass("class" + index);
});

Alterative #2

you can add a custom attribute to your <li> items

<li classToApply="class1">First Clickable Item</li>
<li classToApply="class2">Second Clickable Item</li>

$('li').click(function(){
    $("div").setClass($(this).attr('classToApply'));
});

Worth Mentioning

Both my example and the one provided by Wojciech require The jQuery Library

Upvotes: 0

Wojciech Jasiński
Wojciech Jasiński

Reputation: 1490

You should give some code example. If I were you I would use jQuery. There are click, toggle events and many selectors to choose those divs.

The example:

$("li:first").click(function() {
    $("div").setClass("class1");
});
$("li:eq(1)").click(function() {
    $("div").setClass("class2");
});

Upvotes: 3

Related Questions