admin管理员组文章数量:1356294
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>
本文标签: htmlHow to change innerHTML on multiple elements JavaScriptStack Overflow
版权声明:本文标题:html - How to change .innerHTML on multiple elements? JavaScript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744031625a2579013.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论