Link to home
Start Free TrialLog in
Avatar of splanton
splantonFlag for United Kingdom of Great Britain and Northern Ireland

asked on

Javascript changing attributes of a css style via the classname

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.
Avatar of Gurvinder Pal Singh
Gurvinder Pal Singh
Flag of India image

ASKER CERTIFIED SOLUTION
Avatar of Anuradha Goli
Anuradha Goli
Flag of Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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
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