user2800382
user2800382

Reputation: 259

About getElementsByTagName

I'm attempting to have an alert box pop up every time a user clicks a link on the page - just doing this for practice for better conceptual understanding - and I can't get it to work for all ("a") tags. I can have it work for one ("a") tag if I specify i.e: getElementsByTagName("a")[0]... however I cannot get all a tags to respond in the same way.

Here is the code

function links() {
    if(!document) return false;
    var link = document.GetElementsByTagName("a")[0];
    link.onclick = function() {
                       alert("hi");
                   }
}

I tried document.getElementsByTagNAme("a")[0:4] thinking it might work like python but that didn't do it. Can someone help me out?

Thanks!

Upvotes: 0

Views: 110

Answers (2)

lampshade
lampshade

Reputation: 2816

You can try it like this:

var link = document.getElementsByTagName("a");

for (var i = 0, j = link.length; i < j; ++i) {
    link[i].onclick = function() {
        alert("hi");
    }
}

Here's a jsfiddle: http://jsfiddle.net/v3f7U/

Upvotes: 0

Bucket
Bucket

Reputation: 7521

document.getElementsByTagName() returns an array of elements that match that tag. Since you are referencing the 0th element, only the first <a> tag will be affected.

To fix this, you can loop through the array and apply the onclick handle to each element.

Upvotes: 1

Related Questions