PDA

View Full Version : DOM getElementById vs. getElementByClass???


sugar2
05-17-2005, 06:54 PM
hi, im using this embedded behaviour, but it enforce me to use with a <ul ID=" "> because it use document.getElementById sentences, any idea of how can i edit that code for can be usable for <ul CLASS=" ">, i tried with using of getElementByClass but it didnt work, as you can see im just new to DOM and javascript.

<script type="text/javascript"><!--//--><![CDATA[//><!--

sfHover = function() {
var sfEls = document.getElementById("nav").getElementsByTagName("LI");
for (var i=0; i<sfEls.length; i++) {
sfEls[i].onmouseover=function() {
this.className+=" sfhover";
}
sfEls[i].onmouseout=function() {
this.className=this.className.replace(new RegExp(" sfhover\\b"), "");
}
}
}
if (window.attachEvent) window.attachEvent("onload", sfHover);

//--><!]]></script>

any help and advice will be apreciated

MikeFoster
05-18-2005, 05:51 AM
Have a look at here (http://www.codingforums.com/showthread.php?t=58899)

jscheuer1
05-18-2005, 06:24 AM
That's an interesting approach but, more involved than it might need to be. True, there is no getElementsByClassName. I've used this approach (run onload as your example is):

function activateLiItems(){
var liItems=document.getElementsByTagName('li');
for (var i=0; i<liItems.length; i++) {
if (liItems[i].className=='sfhover'){
liItems[i].onmouseover=function(){
write your mouseover
code here
}
liItems[i].onmouseout=function(){
write your mouseout
code here
}
}
}
}Now, I prefer to just put things directly into these mouseover/mouseout functions, things like:

this.style.color='red';

or the ever popular:

this.innerHTML=this.name;

Which, to be really effective, requires a global (or at least top function) variable to store the original text in for later retrieval. However, if you just want to use this in conjunction with a style sheet, you can just change the element's id, or its class name, as once the script runs, it will not run again without a reload, and that changes all the class names back to the originals.