...

View Full Version : Apply CSS via ECMASCript/JavaScript



w0lf42
06-02-2005, 05:47 PM
I am attempting to cycyle through a few classes and in my attempt to build a tabbed module.

I am using the following XHTML:
<div id="moduleName">
<ul class="tabs">
<li class="tab1"><a href="#" onclick="moduleSwitcher('moduleName', '1'); return false;">panel1</a></li>
<li class="tab2"><a href="#" onclick="moduleSwitcher('moduleName', '2'); return false;">panel2</a></li>
</ul>

<div class="panels">
<div class="panel1">
panel one
</div>
<div class="panel2">
panel two
</div>
</div>
</div>

And the following for my javascript:
function moduleSwitcher(moduleName, activateNumber) {
// define active tab/panel
var activePanel = "panel" + activateNumber;
var activeTab = "tab" + activateNumber;

// obtain module and child nodes
var myElementID = document.getElementById(moduleName);
var moduleChildren = myElementID.childNodes;

for( i = 0; i < moduleChildren.length; i++ ) {
if ( moduleChildren[i].className == "tabs") {
var moduleChildrenChild = moduleChildren[i].childNodes;
for( i = 0; i < moduleChildrenChild.length; i++ ) {
if ( moduleChildrenChild[i].className == activeTab) {
// apply active class to activated tab
alert(activeTab);
} else {
// apply passive class all non-activated tabs
}
}
}
}
} // end function

Where the two comments are, I want to apply some style to a particular section of xhtml code:
// apply active class to activated tab
// apply passive class all non-activated tabs

If div's had IDs I could the following code:
document.getElementById("panel1").style.display='block';

This would show or hide ( display: none; ).

I know how to apply css to IDs with JavaScript, but I don't understand how to accomplish this with classes. Any suggestions?

Basscyst
06-02-2005, 06:00 PM
Look into getElementsByTagName('tag'). Which returns an array of all elements of the specified type. Then loop through the array and analyze the class. When you have the desired class, apply the modified style. Does that help?

Basscyst



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum