Question

As a frist year student we just learned how to use DOM instead of document.write to display our elements.

I have a loop and i want it to display multiple elements after it goes through all of them but it always displays the last one so i am guessing the previous entries are being overwritten?

Here's the piece of the code:

for(var i=0;i<shows.length;i++){  
    if(fgenCTRL.value===films[i].genre)
    {

     filmDiv.innerHTML=shows[i].title+"<br>";

    }

}

It should display 2 elements as an output but it only displays one. Please excuse my poor use of English and Coding Skills.

Was it helpful?

Solution 2

Well yeah in your code, you just replace your value, try using this code.

for(var i=0;i<shows.length;i++){  
    if(fgenCTRL.value===films[i].genre)
    {

     filmDiv.innerHTML=filmDiv.innerHTML+shows[i].title+"<br>";

    }

}

OTHER TIPS

for(var i=0;i<shows.length;i++){  
    if(fgenCTRL.value===films[i].genre)
    {

     filmDiv.innerHTML+=shows[i].title+"<br>";

    }

}

you have to add the new value , not set each time.

Yes, setting the .innerHTML properties overwrites any previous value for that property.

If you want to append your info to it, you have to code it to append by adding to the previous HTML, not overwriting the previous value (note the use of += here).

for(var i=0;i<shows.length;i++){  
    if(fgenCTRL.value===films[i].genre) {
      filmDiv.innerHTML += shows[i].title+"<br>";
    }
}

Though generally, it is better NOT to use .innerHTML this way because you are repetitively converting everything from DOM elements to HTML, adding something to the HTML, then parsing everything back to DOM elements again, creating all new DOM elements and getting rid of all the previous DOM elements.

It is better to just use .appendChild() to append new DOM elements, leaving your previous DOM elements in place rather than recreating everything every time like this:

for(var i=0;i<shows.length;i++){  
    if(fgenCTRL.value===films[i].genre) {
      filmDiv.appendChild(document.createTextNode(shows[i].title));
      fileDiv.appendChild(document.createElement("br"));
    }
}

innerHTML is a DOM property that contain a string. It is not a function that add something like appendChild.

You need to concatenate the string if you don't want to override it

filmDiv.innerHTML += shows[i].title+"<br>";
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top