As soon as I made a start on this project I notice I cannot change the .innerHTML on more than one element. It only outputs the first line. Why is this?
document.getElementById('balance').innerHTML = 'Balance: ' + '100';
document.getElementById('tickets').innerHTML = 'Tickets: ' + '100';
<div id='balance'/>
<div id='tickets'/>
<div id='buy'/>
<div id='pot'/>
As soon as I made a start on this project I notice I cannot change the .innerHTML on more than one element. It only outputs the first line. Why is this?
document.getElementById('balance').innerHTML = 'Balance: ' + '100';
document.getElementById('tickets').innerHTML = 'Tickets: ' + '100';
<div id='balance'/>
<div id='tickets'/>
<div id='buy'/>
<div id='pot'/>
Share
Improve this question
asked Dec 28, 2017 at 19:55
sweetrollsweetroll
3413 silver badges13 bronze badges
3 Answers
Reset to default 5That's because your markup is wrong. The <div>
tag is not self-closing, so you cannot close it with />
.
You have to use a closing tag, like this:
<div>
</div>
Since you have your markup wrong, HTML will try and fix things and it'll put every div inside the one before it.
This is what happens:
div{
margin: 3px;
padding: 10px;
background: blue;
border: 1px solid black;
}
<div id='balance'/>
<div id='tickets'/>
<div id='buy'/>
<div id='pot'/>
This is the generated markup:
When you replace the innerHTML of the first div, the divs inside will be removed from the DOM.
Try opening and closing correctly the Content Division elements:
document.getElementById('balance').innerHTML = 'Balance: ' + 100;
document.getElementById('tickets').innerHTML = 'Tickets: ' + 100;
<div id="balance"></div>
<div id="tickets"></div>
<div id="buy"></div>
<div id="pot"></div>
That's because your markup is wrong. The <div>
tag is not self-closing, so you cannot close it with />
. Since you didn't close the tags, the browser will close them at the end, which makes them nested in each other, and when you changed the innerHTML
of the first tag, you actually replaced all the three nested tags so they no longer exist and the second JavaScript line fails.
Explicitly close the tags and your code will work:
document.getElementById('balance').innerHTML = 'Balance: ' + '100';
document.getElementById('tickets').innerHTML = 'Tickets: ' + '100';
<div id='balance'></div>
<div id='tickets'></div>
<div id='buy'></div>
<div id='pot'></div>