Hey all, I know you can reference certain elements buy its ID many different ways! Is it possiblle to do the same with class names? I know I have seen javascript manipulating class names somewhere, .className or something? Thanxs 4 your time1
| SitePoint Sponsor |


Hey all, I know you can reference certain elements buy its ID many different ways! Is it possiblle to do the same with class names? I know I have seen javascript manipulating class names somewhere, .className or something? Thanxs 4 your time1
There is no getelementsbyclassname function, but you could make it yourself quite easily:
Code:<script type="text/javascript"> function getclassname(arg){ var temparray=new Array(); var x=document.getElementsByTagName('*'); xtemp=x.length; for (var i=0;i<xtemp;i++){ if (x[i].className==arg){ temparray.push(x[i]); }; } return temparray; } document.getElementsByClassName=getclassname; alert(document.getElementsByClassName('test')[1].innerHTML); </script>
Ah, mw22 you beat me to the punch. Oh well, here's the post I was working on:
Javascript uses the id attribute of the HTML element to access the Element object and it's properties, for example:
The id attribute of each element must be unique. A CSS class can be applied to more than one element, for example:Code:eleObj = document.getElementById(id);
getElementById is the most direct way to get an object reference when you want a specific Element object corresponding to a unique id. Sometimes you need to get a list or array of all Element objects with something in common - for example all elements whose class attribute contains the string 'content'. The following provides that capability:Code:<style> .content { color:#000; background:#ccc; } </style> </head> <body> <div id='d1' class='content'>d1</div> <div id='d2' class='content'>d2</div>
Code:<html> <head> <style> #d1 { color:#000; background:#ccc; margin:1em; } #d2 { color:#ccc; background:#000; margin:2em; } .content { font-family:verdana,arial; text-size:14px; } </style> <script> window.onload = function() { var eleList = document.getElementsByClassName('content'); var i, s = "Elements whose class attribute contains 'content':\n\n"; for (i=0; i<eleList.length; ++i) { s += eleList[i].id + '\n\n'; } alert(s); } document.getElementsByClassName = function(clsName) { var i, elements, found, re; re = new RegExp("\\b"+clsName+"\\b"); found = new Array(); elements = document.all ? document.all : document.getElementsByTagName('*'); for (i=0; i<elements.length; ++i) { if (elements[i].className.search(re) != -1) { found[found.length] = elements[i]; } } return found; } </script> </head> <body> <div id='d1' class='content'>d1</div> <div id='d2' class='content'>d2</div> </body> </html>


Great Mike, You got a direct hit thats exactly Im lookin for! The whole thing makes sence but I dont understand what the
re = new RegExp("\\b"+clsName+"\\b" );
line does! I relly should learn more about regular expressions! Anyway Thanks again Mike and MW22! I cant thank you enough!


I cant get over how awesome this script is! I can even return css style for every ID in a class
I'm literally Jumping for Joy! Thanxs Again!Code:<html> <head> <style> #d1 { color:#000; background:#cccccc; margin:1em; } #d2 { color:#ccc; background:#000000; margin:2em; } .content { font-family:verdana,arial; text-size:14px; } </style> <script> function getClass(name) { var eleList = document.getElementsByClassName(name); var i, s = ""; for (i=0; i<eleList.length; ++i) { s += eleList[i].currentStyle.backgroundColor + '\n\n'; } if(s==""){ s+="That is Not A Class Name In This Document!"; } alert(s); } document.getElementsByClassName = function(clsName) { var i, elements, found, re; re = new RegExp("\\b"+clsName+"\\b" ); found = new Array(); elements = document.all ? document.all : document.getElementsByTagName('*'); for (i=0; i<elements.length; ++i) { if (elements[i].className.search(re) != -1) { found[found.length] = elements[i]; } } return found; } </script> </head> <body> <form> <input type="text" name="myClass"> <input type="button" value="Do It" onclick="getClass(this.form.myClass.value)"> <form> <div id='d1' class='content'>d1</div> <div id='d2' class='content'>d2</div> </body> </html>
PS. Hey Mike did you write this one the fly!
The regex is because elements can have more than 1 class, a \b is a word break in PCRE.
Who walks the stairs without a care
It shoots so high in the sky.
Bounce up and down just like a clown.
Everyone knows its Slinky.
Thanks Poop_Shoot,
No, I didn't write that 'on the fly'. It was something I had lying around. Actually the original version may have come from Tim Scarfe - I can't really remember.![]()
Are the word boundary characters really needed for the search()?? You could just use indexOf() for this, no? Should be less expensive than a regex operation.
Well, I did write it sort of on the fly. but I forgot that you could have multiple classes for the same element.
Good catch Mike.
Maybe this is something of interest for the topic starter also:
http://simon.incutio.com/archive/200...entsBySelector
Yep, I think beetle's right. indexOf() seems to be a better choice there.


That is quite an interesting link mw22! If only I understood how I could write scripts like that! Well Ill keep plugin away!
well, I've thought about it some more and I know now why MikeFoster used the regex w/word boundaries
.red { color: red }
.redAndBig { color: red; font-size: 120% }
Those will both trigger a find when looking for "red" with any other method.
Well done Mike - you were right after all.![]()
I hope nobody's writing their CSS classes like that!![]()
I wrote something similar, however used match() instead of search() as match() just returns true or false.
Who walks the stairs without a care
It shoots so high in the sky.
Bounce up and down just like a clown.
Everyone knows its Slinky.
mw22, very interesting link - thanks!
Thanks beetle - but I can't really remember if I wrote it. I may have modified it but I think Tim wrote the original.
Poop_Shoot, yes I agree, it's a very useful function.
Actually, that couldn't be further from the truth.Originally Posted by Jeff Lange
A quote from the guideAdditionally, more words about match() from MSDNNote <A id=1198153 name=1198153>If you execute a match simply to find true or false, use String.search or the regular expression test method.As you can see, the results of running match() are far more complicated than a simple boolean return.If the match method does not find a match, it returns null. If it finds a match, match returns an array, and the properties of the global RegExp object are updated to reflect the results of the match.
The array returned by the match method has three properties, input, index and lastIndex. The input property contains the entire searched string. The index property contains the position of the matched substring within the complete searched string. The lastIndex property contains the position following the last character in the last match.
Did you have the two flip-flopped in your head?





Nice bit of work. Used the method to border divisions with a pic border instead of usual inset/outset etc.cheers....... been needing a bit of code like that.Code:function borderClass() { var x=document.getElementsByTagName('*'); for(i=0;i<x.length;i++) { if(x[i].className.indexOf("border")>-1) { var h=x[i].style.width;var v=x[i].style.height x[i].innerHTML+='<img alt="UnitingRhythms" class="tlc" style="width:'+h+';height:20px" src="images/bamvsmlt.gif">'+ '<img alt="UnitingRhythms" class="trc" style="width:20px;height:'+v+';" src="images/bamvsmlr.gif">'+ '<img alt="UnitingRhythms" class="brc" style="width:'+h+';height:20px" src="images/bamvsmlb.gif">'+ '<img alt="UnitingRhythms" class="blc" style="width:20px;height:'+v+';" src="images/bamvsmll.gif">'+ '<img alt="UnitingRhythms" class="tlc" src="images/bamcsmltl.gif">'+ '<img alt="UnitingRhythms" class="trc" src="images/bamcsmltr.gif">'+ '<img alt="UnitingRhythms" class="brc" src="images/bamcsmlbr.gif">'+ '<img alt="UnitingRhythms" class="blc" src="images/bamcsmlbl.gif">' }}}
Last edited by Markdidj; Dec 21, 2004 at 08:29.
LiveScript: Putting the "Live" Back into JavaScript
if live output_as_javascript else output_as_html end if
I had to use this for something and I made a few modifications:
Code:/* xGetElementsByClassName() Returns an array of elements which are descendants of parentEle and have tagName and clsName. If parentEle is null or not present, document will be used. if tagName is null or not present, "*" will be used. */ function xGetElementsByClassName(clsName, parentEle, tagName) { var elements = null; var found = new Array(); var re = new RegExp('\\b'+clsName+'\\b'); if (!parentEle) parentEle = document; if (!tagName) tagName = '*'; if (parentEle.getElementsByTagName) {elements = parentEle.getElementsByTagName(tagName);} else if (document.all) {elements = document.all.tags(tagName);} if (elements) { for (var i = 0; i < elements.length; ++i) { if (elements[i].className.search(re) != -1) { found[found.length] = elements[i]; } } } return found; }
I think that's exactly what happened, lol. (Stupid memory)Did you have the two flip-flopped in your head?
Who walks the stairs without a care
It shoots so high in the sky.
Bounce up and down just like a clown.
Everyone knows its Slinky.
Bookmarks