最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - How to change .innerHTML on multiple elements? JavaScript - Stack Overflow

programmeradmin0浏览0评论

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
Add a ment  | 

3 Answers 3

Reset to default 5

That'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>

发布评论

评论列表(0)

  1. 暂无评论