Log in

View Full Version : Quick Question about getElementsByTag



cursed
12-09-2009, 02:29 AM
Sorry, not good at javascript at all, I'm more of a PHP person.
What's wrong with this code?




tds = document.getElementsByTagName("a");
for( var x=0; x < tds.length; x++ ) {
tds[x].onclick = updatebox(event);
}


function updatebox(evt) {

alert('Hi DynamicDrive!')


}

<a href="http://www.google.com">doesn't work</a>
<a href="http://www.google.com" onclick="updatebox(event)">does work</a>

anexample o f an image clicking
<a href="http://www.google.com" onclick="updatebox(event)"><img

src="http://www.google.com/images/nav_logo7.png"></img></a>



thanks in advance.

bluewalrus
12-09-2009, 02:37 AM
I don't think any of them are working the way you want them to. The ones that work only work because they have the onclick and that is only running through



function updatebox(evt) {
alert('Hi DynamicDrive!')
}

What is the first part suppose to do?


tds = document.getElementsByTagName("a");
for( var x=0; x < tds.length; x++ ) {
tds[x].onclick = updatebox(event);
}

Schmoopy
12-09-2009, 03:06 AM
I have a limited knowledge of JavaScript, but this seemed to do the trick:



<html>
<head>
<script type="text/javascript">
function updatebox() {
alert('Hi DynamicDrive!')
}
</script>
</head>

<body>
<a href="http://www.google.com">doesn't work</a>
<a href="http://www.google.com">does work</a>

anexample o f an image clicking
<a href="http://www.google.com"><img

src="http://www.google.com/images/nav_logo7.png"></img></a>
<script type="text/javascript">
tds = document.getElementsByTagName("a");
for( var x=0; x < tds.length; x++ ) {
tds[x].setAttribute('onclick', 'updatebox()');
}
</script>
</body>
</html>


@Bluewalrus - The for loop goes through all the elements with the anchor tag <a>, then sets the onclick event of each of them to call "updatebox", which in turn alerts "Hi DynamicDrive!" before proceeding to the webpage specified.

jscheuer1
12-09-2009, 04:30 AM
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript">
onload = function(){
function updatebox(e){
e = e || window.event;
var t = e.target || e.srcElement;
while(t.parentNode && t.nodeName !== 'A'){
t = t.parentNode;
}
if(t.href){
alert("You've clicked a link to " + t.href);
}
return false;
}
var tds = document.getElementsByTagName('a'), i = 0;
for(i; i < tds.length; ++i){
tds[i].onclick = updatebox;
}
};
</script>
</head>
<body>
<div>
<a href="http://www.dynamicdrive.com">didn't work (does now)</a>
</div>
<div>
<a href="http://www.yahoo.com">does work</a>
</div>
<div>
an example of an image clicking
<a href="http://www.google.com"><img src="http://www.google.com/images/nav_logo7.png" alt=""></a>
</div>
</body>
</html>