Javascript changing attributes of a css style via the classname

splanton
splanton used Ask the Experts™
on
Hi,
I have a requirement to alter the background image of a sliding doors tab menu when the menu is 'active'.

One solution would be to write a javascript script to alter the background image of the item in question.

Up until now i have been using the 'getElementById' method for setting the style of an item via it's 'id'.

I would like to be able to alter the background image of every item on the form that is using a particular 'class' rather than 'id'

Example:

CSS
.image1 {background-image: url(/image1.png);}
.image2 {background-image: url(/image2.png);}


HTML
<div class = 'image1'>
</div>

<div class = 'image2'>
</div>

<div class = 'image1'>
</div>

I would like to change all the backgrounds with class 'image1' to a different image.

Is this possible with javascript?

I know the immediate response will be to tell me to use id's and in the example above I would have to agree, but in the code I aM currently modifying there are a series of complicated nested elements with varying backgound images and the CSS references elements that currently have no Id's - to add them would create a sea of Id's whose only purpose would be to facilitate the javascript. I would like to avoid that cleanly if possible.
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Systems Development / Support Specialist
Commented:
You can use
elements = document.getElementsByClassName(names);
Kusala WijayasenaSoftware Engineer

Commented:
Try this:

function changeBackgroundImage(className, pathToImage) {
	var classes = document.styleSheets[0].rules || document.styleSheets[0].cssRules;
	for(var x=0;x<classes.length;x++) {
		if(classes[x].selectorText==className) {
			classes[x].style.backgroundImage = 'url(' + pathToImage + ')';
		}
	}
}

//call function like this
changeBackgroundImage(".image1", "image3.png");

Open in new window


-Kusala

Commented:
I'd recommend you to utitlize the power of jQuery

Simply add this line to your page's header

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>

Open in new window


and then you can easily find and change your elements (in this case by class name) just like this

$('.image1').css('background-image', 'url(path_to_new_image)');

Open in new window


You can wrap up it in a function like this

function changeBackgroundImage(clsName, imgPath) {
   $('.'+clsName).css('background-image', 'url('+imgPath+')');
}

//call
changeBackgroundImage('image1', '/path/to/my/image.png');

Open in new window

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial