Changing background color of multiple div's at the same time
i have say 20 div's. Is there a way that i can change the background-color of all the divs at the same time without doing a loop. Maybe if i named the divs all the same? How do i do this?
Don't know if there's a way to just grab the group name and change the bgcolor. Thanks for your inp开发者_开发知识库ut, greatly appreciated!
give them a class like <div class='something'>...</div>
then you can do :
$('.something').addClass('new-bg');
in your CSS you will have :
.new-bg {
background-color: red;
}
Yep, working with the dom is what jQuery does best. The simplest approach would be
$('div').css('background-color', '#f0f');
That'll change all the background colours to a lovely shade of pink.
If you only want to change some of the div's, you can give them a class
<div class="pickme'>...</div>
Then change your selector to something like
$('div.pickme').css('background-color', '#f0f');
Otherwise, a quick read through the jQuery selector docs, or some of the gentler introductions to jQuery, should get you on the right track
Your going to want to use a class attribute.
<div class="group-1"><!-- content --></div>
<div class="group-1"><!-- content --></div>
<div class="group-1"><!-- content --></div>
<div class="group-1"><!-- content --></div>
Then, with jQuery you can do:
$(".group-1").css('background-color','#ccc');
See jQuery.css()
If you need to change the value with a specific value, you could do the following:
First, you would need to have a class, like 'bgGroup', on your respective div's, such as:
HTML...
<div class='bgGroup'>div #1</div>
<div class='bgGroup'>div #2</div>
<div class='bgGroup'>div #3</div>
and change the background color on your scripts...
$('.bgGroup').css('background-color', '#cccccc');
On the other hand, if you had a particular CSS class, you could just add the class that contains the background color you desire. There could be more plumbing with this, like removing other classes and then adding the desired one if you have to change it numerous times.
You'll need some CSS...
.old-bg-class {
backgroundColor: #ffffff;
}
.new-bg-class{
backgroundColor: #cccccc;
}
some class attributes on your HTML...
<div class='bgGroup'>div #1</div>
<div class='bgGroup'>div #2</div>
<div class='bgGroup'>div #3</div>
and change the background color on your scripts...
$('.bgGroup').addClass('new-bg-class');
精彩评论