admin管理员组文章数量:1332872
How do I do this? Please help if you could,
<div id="user"> one </div>
<div id="user"> two </div>
<script>
document.getElementById('user').innerHTML = "three";
</script>
I was looking if we can replace all the divs with same ID with "three"
How do I do this? Please help if you could,
<div id="user"> one </div>
<div id="user"> two </div>
<script>
document.getElementById('user').innerHTML = "three";
</script>
I was looking if we can replace all the divs with same ID with "three"
Share Improve this question edited Mar 13, 2014 at 14:15 Zafar 3,4244 gold badges30 silver badges45 bronze badges asked Mar 13, 2014 at 14:13 user3057739user3057739 311 silver badge5 bronze badges 1-
4
this is not a valid
HTML
. id should be unique. useclass
instead. – Zafar Commented Mar 13, 2014 at 14:16
4 Answers
Reset to default 4Although it's highly discouraged and invalid to use identical IDs in HTML, there is a way to do it in most browsers:
var elements = document.querySelectorAll('[id="user"]');
for(var i = 0; i < elements.length; i++) {
elements[i].innerHTML = "three";
}
Same id on multiple elements is no good idea, due to id's beeing declared unique in html documentation. Better would be to use classes.
Then in vanilla JS you can do the following:
var users = document.getElementsByClassName('user');
for (var i = 0; i < users.length; ++i) {
var user = users[i];
user.innerHTML = '<p>Hello out there!</p>';
}
or use jQuery which is much easier.
By w3c standart you must use unique id's.
http://www.w3/TR/html401/struct/global.html
Please, see note 7.5.2 Element identifiers: the id and class attributes
You can use class name.
As others have stated, multiple id's is not proper HTML. Instead you can use classes:
<div class="user"> one </div>
<div class="user"> two </div>
You can then select them using the following:
document.querySelectorAll('.user').forEach(el => {
// do things with each element here
});
document.querySelectorAll('.user').forEach(el=>{
el.style.background = "green";
})
<div class="user"> one </div>
<div class="user"> two </div>
本文标签: javascriptReplacing all the innerHTML with the same ID using JavasScriptStack Overflow
版权声明:本文标题:javascript - Replacing all the innerHTML with the same ID using JavasScript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742308570a2450411.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论