I found out so far how to replace element by another element on a html-page. But my function is working in a strange way. First it replaces first and third image. If i invoke it again, it replaces only the second image. Pressing button again makes finally the last fourth image replace. Somebody any ideas about that? Here's the source: http://pastie.org/5502630 And here you can see how it works: http://clubnights.square7.ch/webtech/a2.html
You're modifying the list of images as you're iterating through it. So when you try to access the images array it's not what you think it is! Below is a possible workaround..
function Convert()
{
images = window.document.getElementsByTagName('img');
var num_images = images.length;
for (var i = 0; i < num_images; i++)
{
var image = images[0];
textReplacement = document.createTextNode(image.getAttribute('alt'));
image.parentNode.replaceChild(textReplacement, image);
}
}
With each pass through the for
loop, you remove the first image from the images[]
array. This changes both the array contents and the array length set as the conditional in your loop.
For example, your first loop through removes images[0]
, ausdruck_1.gif -- but now images.length equals 3, not 4, and the contents of the array are now:
images[0]=ausdruck_2.gif
images[1]=ausdruck_3.gif
images[2]=ausdurck_4.gif
Your second pass through the loop removes images[1]
-- now ausdruck_3.gif -- and further changes the length of the images array to 2, so the next increment of i to 2 causes the loop to exit.
I created a jsfiddle showing a possible solution of changing your for statement to:
for(i = images.length-1; i >=0; i--)
and looping through the images in reverse order.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.