Henk Z Henk Z - 1 year ago 69
Javascript Question

Javascript not working with multiple rows

For some reason my Javascript code does not work.
But when I remove some of the Javascript lines, it works fine.

What am I doing wrong?


<span id="21" class="addon-price">€ 0,00 p.m.</span>
<span id="57" class="addon-price">€ 0,00 p.m.</span>


document.getElementById("17").innerHTML = "Gratis";
document.getElementById("18").innerHTML = "Gratis";
document.getElementById("19").innerHTML = "Gratis";
document.getElementById("20").innerHTML = "Gratis";
document.getElementById("21").innerHTML = "Gratis";
document.getElementById("47").innerHTML = "Gratis";
document.getElementById("52").innerHTML = "Gratis";
document.getElementById("57").innerHTML = "Gratis";
document.getElementById("62").innerHTML = "Gratis";

JSFiddle: https://jsfiddle.net/4e362pg3/5/

Answer Source

The JavaScript code is fine. You are getting exceptions, because you are trying to set the innerHTML of tags which are not there. Based on your code, the only two which will successfully work are the ones which try and set the span tags of 57, and 21. On all the others, the JavaScript throws an exception and stops the execution.

To fix it, all you need to do is wrap each set in a conditional to see if the element exists before trying to set the value.

if(document.getElementById("17")) {
    document.getElementById("17").innerHTML = "Gratis";

Here is an example with a couple of the elements in the conditional.