Sasha13
Sasha13

Reputation: 3

javascript. my for loop stops after one iteration when enclosed in a function

here's my problem. When my code is embedded within an html page, between body tags, it executes as it's suppose to : displays 12 lines of text (for loop goes 12 times);

but, when I enclose the code in a function, import it from an external js file, and try to envoke it with an onclick or onsubmit event, it stops after the first iteration.

this is the code embedded in an html file:

var all_imgs = document.getElementsByTagName('img');

        for(var i=0; i<all_imgs.length; i++){

            var item = all_imgs[i].src;
            var item_limit = item.length-4;
            var item_limit2 = item.length-6;

            var selected = item.substring(item_limit, item_limit2);

            if (selected == 'on') {
                document.write('image ' + i + ' with url : ' + item + ' is ');
                document.write('chosen');
                document.write('<br>');
            }
            else {
                document.write('image ' + i + ' with url : ' + item + ' is ');
                document.write('not chosen');
                document.write('<br>');
            }

        }  

and the output:

image 0 with url : www.../thumb2_on.jpg is CHOSEN  
image 1 with url : www.../thumb2_off.jpg is NOT CHOSEN  
image 2 with url : www.../thumb2_off.jpg is NOT CHOSEN  
image 3 ...  
.  
.  
.  
image 11 with url : www.../thumb2_on.jpg is CHOSEN  

this is the code from the external js file :

function selectedImages(){
        var all_imgs = document.getElementsByTagName('img');

        for(var i=0; i<all_imgs.length; i++){

            var item = all_imgs[i].src;
            var item_limit = item.length-4;
            var item_limit2 = item.length-6;
            //document.write(item_limit);
            //document.write(item_limit2);

            var selected = item.substring(item_limit, item_limit2);

            if (selected == 'on') {
                document.write('image ' + i + ' with url : ' + item + ' is ');
                document.write('chosen');
                document.write('<br>');
            }
            else {
                document.write('image ' + i + ' with url : ' + item + ' is ');
                document.write('not chosen');
                document.write('<br>');
            }

        }
    }

the onclick event from the html file :

<a href="#" onclick="javascript:selectedImages();">test</a>

or

<form action="#" method="post" onsubmit="javascript:selectedImages();">

and the print out :

image 0 with url : www.../thumb2_on.jpg is CHOSEN

Upvotes: 0

Views: 641

Answers (1)

Guffa
Guffa

Reputation: 700910

That is because you are using document.write after the page has loaded. It will replace the current page with the new content, so when you get to the second iteration in the loop there aren't any images in the page any more.

Upvotes: 2

Related Questions