View Full Version : getElementsByTagName skips every 2nd tag!

Mar 19th, 2007, 11:28 PM
I have some img tags in my HTML code, and I am trying to implement some manipulation on each image. Thing is, when using document.getElementsByTagName('img'), the JS engine skips every 2nd img tag, so I get an array with only half of the deal.

What do you think?

Mar 20th, 2007, 12:02 AM
document.getElementsByTagName('img') will build a collection of all the img elements, in the loading sequence (counting from top to the bottom), as you can see the page when give it a "View > Page Souce" command. There is no way to skip any of them... Keep in mind that the order is the real coding order, that is all...

Mar 20th, 2007, 12:37 AM
I know that, lol.
So what could be it? Here's the entire JS code:

var images = document.getElementsByTagName('img');
for (var i = 0; i < images.length; i++)
var img = images[i];
var imgName = img.src.toLowerCase()
if ((imgName.substring(imgName.length-3, imgName.length) == 'png'))
var imgID = (img.id) ? "id='" + img.id + "' " : ""
var imgClass = (img.className) ? "class='" + img.className + "' " : ""
var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' "
var imgStyle = "display:inline-block;" + img.style.cssText
if (img.align == "left") imgStyle = "float:left;" + imgStyle
if (img.align == "right") imgStyle = "float:right;" + imgStyle
if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle
var strNewHTML = "<span " + imgID + imgClass + imgTitle
+ " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"
+ "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
+ "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>"
img.outerHTML = strNewHTML

Mar 20th, 2007, 03:13 PM
outerHTML is not a DOM standard method (and it is an IE only), thus it does not really insert new elements into the DOM tree. Use DOM methods to create elements.

Mar 20th, 2007, 03:20 PM
Got it. Thanks. Actually, I've switched to a different solution, better, which eats less resources. However, it's causing some trouble in IE (again).

Please be kind and take a look: http://www.codingforums.com/showthread.php?t=110266

Mar 20th, 2007, 09:13 PM
The NodeList that getElementsByTagName returns is live. In each iteration, you are removing an image. Thus, list.length is decreased by 1, and the image that the variable i refers to is the next image. Thus, incrementing it skips it.

Mar 20th, 2007, 09:29 PM
Oh, yes, if you want to remove the elements from a collection, you should do it using a backward loop:

var imag=document.getElementsByTagName('img');
for(var i=imag.length-1;i>=0;i--){

Mar 21st, 2007, 12:19 AM
Thanks guys, you made it very clear ;)