Why isn't this loop working ?

Recommended Answers

All 9 Replies

Works for me, provided you change write to alert

It's not working on my end. The code won't work in JSBin either !

Try replacing your js with this...

var one = document.getElementsByTagName("a");
if (one.length) 
    alert("correct, four anchors"); 


What do you mean by "not working"? When you ask or report a bug or not working program, you should explain 3 things -- 1)Input data, 2)Expected output, and 3)What error you are getting, and 4)Explain what is not working (i.e. no alert display, the browser hung up, etc).

At the glance, the script should work BUT it could cause an unexpected behavior. If the page does not contain an anchor tag, you will get "undefined" which can't be used with length() function. You need to think about what you are testing...

commented: nods +14

It works ! What if I removed an anchor tag can I use an array to check how many anchors there are ?

Use one.length

one.length is being used. When I remove an anchor the condition tells me there is four anchors when there are only three.

So use the one.length property within the alert method.


alert("there are " + one.length + " anchors");

Oh, thanks :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.