Closed Thread Icon

Preserved Topic: Applying properties to classes (Page 1 of 1) Pages that link to <a href="https://ozoneasylum.com/backlink?for=8744" title="Pages that link to Preserved Topic: Applying properties to classes (Page 1 of 1)" rel="nofollow" >Preserved Topic: Applying properties to classes <span class="small">(Page 1 of 1)</span>\

 
ZOD
Bipolar (III) Inmate

From:
Insane since: Jun 2002

posted posted 07-05-2003 16:16

What is the most efficient way to apply properties, styles ans events to objects with the same classname via javascript?

Dracusis
Maniac (V) Inmate

From: Brisbane, Australia
Insane since: Apr 2001

posted posted 07-05-2003 17:17

myClassName = "myClass"
myDivs = document.getElementsByTagName("div")

for (i=0; i < myDivs.length; i++) {
if (myDivs[i].className == myClassName) {
myDivs[i].style.styleProperty = "styeValue"
}
}

ZOD
Bipolar (III) Inmate

From:
Insane since: Jun 2002

posted posted 07-05-2003 20:33

Thanks. I had done something almost exactly the same but I was hoping there was a way to do it without a loop.

Scott
Bipolar (III) Inmate

From: schillmania.com
Insane since: Jul 2002

posted posted 07-05-2003 23:26

I'm hoping there'll be a getElementsByClassName() in future versions of JS.

Until then you could write your own and possibly append it to the DOM prototype, extending the basic DOM functionality (I haven't actually tried, just using a "globally"-scoped getElementsByClassName() function) .. so you could have it accessible from individual elements too. (eg. document.getElementById('someID').getElementsByClassName('someClassName') );




[This message has been edited by Scott (edited 07-05-2003).]

Slime
Lunatic (VI) Mad Scientist

From: Massachusetts, USA
Insane since: Mar 2000

posted posted 07-06-2003 00:02

The following is a getElementsByClassName function which I've written for my own use. It gets every single element in the document whose className is set to a specific value. It takes into account that className's may be a space-separated list of classes:

// used in function below
function stringisinlist(list,string)
{
var listarray = list.split(/ /);
for (var a=0; a < listarray.length; a++) {
if (listarray[a] == string)
return true;
}
return false;
}
function getElemensByClassName(className)
{
var toreturn = new Array();
getElementsByClassNameHelper(document.getElementsByTagName('html')[0], className, toreturn);
return toreturn;
}
function getElementsByClassNameHelper(node, classname, nodelist)
{
if (node.className && stringisinlist(node.className, classname))
nodelist[nodelist.length] = node;
for (var a=0; a < node.childNodes.length; a++)
getElementsByClassNameHelper(node.childNodes[a], classname, nodelist);
}

ZOD
Bipolar (III) Inmate

From:
Insane since: Jun 2002

posted posted 07-06-2003 04:21

Thanks Slime. I'll be up all night with that one LOL!

« BackwardsOnwards »

Show Forum Drop Down Menu