using javaScript with css

liunx

Guest
Hi, I am working with css for the first time and i was wondering how you use selectors in javascript. I have designed a css layout with one of the columns called .centercolumn and I want to manipulate the background with javaScript. I have used a <div class="centercolumn"> to add the style to my HTML. Coding it in javaScript as document.centercolumn.bgColor doesn't work. I assume there is a way to make it work because so far CSS is awesome. Thank you for any insights.

ScubaHello, please try the following.


<script type="text/javascript">
var div = document.getElementsByTagName("div");
for(i=0; i<div.length; i++){
if(div.className == "centercolumn"){
div.style.backgroundColor="red";
}
}
</script>No dice,

Thanks for the try though. Using JavaScript though I use ClassName to retrieve a css elemnt, so that does help. Thank you,

Scuba :cool:Javascript uses ID to get to specific objects (ID must be unique), NAME to get to several objects but not CLASS. There are useful methods as follows:

document.getElementById(id); // the one object specified by id
document.getElementsByName(nm); // all objects that have name=nm
document.getElementsByTagName(); // all objects of HTML tag
I can see where it would be interesting to get elements by class, but the boys at W3C have not seen fit to do so.So in a CSS document the

.whatever is an object?

Is that how it works?

Thanks again,

ScubaNot always. It is more complicated than that. The things I listed were methods of the document object. They are used to find other objects. Once you find the object you can interrogate its className (if it has one) like the script Jona provided.

This is probably not the place to try and teach you javascript. Try one of the many tutorials available on the web.Scuba Steve, the code I provided won't work unless it is run as a function onload, or if it is placed after the HTML of the DIV it specifies. Put it in the head tag, and run it onload.


<script type="text/javascript">
window.onload = function(){
var div = document.getElementsByTagName("div");
for(i=0; i<div.length; i++){
if(div.className == "centercolumn"){
div.style.backgroundColor="red";
}
}
}
</script>May be able to use document.getElementsByTagName("style").item(0).lastChild.nodeValueOk, that worked now Jona. Thank you.You're welcome.What you're doing is actually called DHTML or Dynamic Hypertext Markup Language - using javascript to manipulate CSS properties.
Now you can add that to your resume :)
 
Back
Top