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. use class instead. – Zafar Commented Mar 13, 2014 at 14:16
Add a ment  | 

4 Answers 4

Reset to default 4

Although 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