Forum Moderators: open

Message Too Old, No Replies

document.getElementsByTagName conflicts in functions

         

pepijn

9:21 am on Jul 19, 2007 (gmt 0)

10+ Year Member



I am loading 3 functions which have to loop through the page looking for anchor tags like this:

function one(){
var e = document.getElementsByTagName("a");
for (var i=0;i<e.length;i++){
e[i].onclick = function(){
if(this.className == "change"){
this.style.display = "block";
}
}
}
}
function two(){
var e = document.getElementsByTagName("a");
for (var i=0;i<e.length;i++){
e[i].onclick = function(){
if(this.className == "add"){
this.style.display = "block";
}
}
}
}

The problem is that the functions will not execute because they all have the onclick event on the anchors. I can prevent this by using getElementById within the function, but that is not always possible. How can i get this to work right so that the onclick is only executed on the right anchor

Arno_Adams

5:45 pm on Jul 19, 2007 (gmt 0)

10+ Year Member



Hi pepijn,

You mean something like this:


function one() {
var e = document.getElementsByTagName("a");
for (var i=0;i<e.length;i++) {
e[i].onclick = function(){
if(this.className == "change"){
this.style.display = "block";
}
else if(this.className == "add"){
this.style.display = "none";
}
}
}
}

HTH, AA

pepijn

10:37 am on Jul 20, 2007 (gmt 0)

10+ Year Member



Hi,

this looks ok!
thanks.