JGeer
JGeer

Reputation: 1852

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?

HTML:

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

Javascript:

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/

Upvotes: 0

Views: 131

Answers (2)

Jeremy Thille
Jeremy Thille

Reputation: 26370

Open your console.

Uncaught TypeError: Cannot set property 'innerHTML' of null

If the element does not exist in your DOM, the selector will return null. null.innerHTML is not defined, it throws an error and crashes the page.

Solution with jQuery (because you used the jQuery tag in your question) :

$("#17").html("Gratis);

This will never crash the page, even if the "17" element is not present.

Upvotes: 2

kemiller2002
kemiller2002

Reputation: 115488

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.

Upvotes: 1

Related Questions