Debt Consolidation - Debt Consolidation - Bad Credit Loans - Debt Consolidation - Debt Consolidation

PDA

View Full Version : Change CSS style with JavaScript


simnorwebdesign
Aug 10th 2007, 4:34 am
Hi, I am currently creating a wordpress theme and as part of the theme there is the option for the user to change the colors of the theme, I am using some javascript to change certain elements of the css, but have come up against a problem.

I need to change the h2 property in the #sidebar div, in the CSS file it looks like this:
#sidebar h2 {
styles here
}

The javascript I am using is this:

<script type="text/javascript">
function changetored(){
document.getElementById("header").style.background = "url(<?php bloginfo('stylesheet_directory'); ?>/images/bannerred.png)";
document.getElementById("page").style.background = "url(<?php bloginfo('stylesheet_directory'); ?>/images/shadowred.png)";
}
</script>


Now this works fine because it is getting the Element, however what I want to change is the background color of not an element but a class (h2) or more particularly #sidebar h2

How would I do this, is getElementById supposed to be something different?
Any help will be greatly appreciated, thank you

Simon North

simnorwebdesign
Aug 10th 2007, 6:04 am
Hi, thank you for the code, unfortunately it didn't work for some reason, if it helps you can find what i am trying to do at http://pcmaclin.com/test/ The bits that I want the background color to change on is the sidebar headers, where it says pages, archives etc.

Jamie18
Aug 10th 2007, 10:33 am
i'm not sure if this would work as i have never tried to do it myself.. but if you gave all of those h2's the same name, say 'h2name', and than used this

document.getElementsByName("h2name").style.background = "url(<?php bloginfo('stylesheet_directory'); ?>/images/bannerred.png)";

it might give you the desired effect. the getElementsByName() function returns all objects with that name.. and therefor maybe you can... however even if this does work i can't say if it's the cleanest solution.

good luck anyways

Drag Racer
Aug 10th 2007, 9:35 pm
document.getElementsByName("h2name").style.background will probable generate an error as getElementsByName() method returns an array. The getElementsByTagName() is also an option.

function changetored(){
var h = getElementsByTagName('h2');
for(var i=0; i<h.length; i++){
h[i].style.background = "url('pathToImg')";
}
}