Skip to content Skip to sidebar Skip to footer

Document.getelementsbytagname("a") Misses A Link

I was working on a script for Greasemonkey (FX7) trying to remove certain links and found out that for some reason one that was present in the source, not hidden or constructed by

Solution 1:

The for...in statement loops through the properties of an object. In this particular case you are iterating over Array object properties. Try to use this script instead:

var links = document.getElementsByTagName("a");
for (var l = 0; l < links.length; l++){
  if (links[l].href == "blah"){ ... }
}

Solution 2:

var links = document.getElementsByTagName('a');
  for (var i=0; i<links.length; i++){
     if (links[i].href.match('blah')){...}
  };

Solution 3:

for … in statements loop through the properties of an object, not only its values, just like @Yuriy said. You'll need to learn some Javascript to understand this (sorry, couldn't find any direct pointer to this part after a few minutes of Googling).

Basically, you need to understand that objects in JS also include “methods”. When you're using a for … in loop, you find an object's values but also its “methods” and other properties.

So, either use @Yuriy's indexed loop… or better, use the hasOwnProperty() method (MDN doc), that allows to avoid the very important caveat @Kolink mentioned.

Your loop should look like:

var links = document.getElementsByTagName('a');
for (var l in links) {
    if (! links.hasOwnProperty(l))
        continue; // this goes straight to the next propertyif (links[l].href == "blah") { ... }
}

Solution 4:

getElementsByTagName ("area") [0] returns the value of its href attribute and not HTMLAnchorElement

Post a Comment for "Document.getelementsbytagname("a") Misses A Link"