Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing all the innerHTML with the same ID using JavasScript

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"

like image 987
user3057739 Avatar asked Feb 12 '26 14:02

user3057739


1 Answers

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";
}
like image 121
T.S. Avatar answered Feb 14 '26 02:02

T.S.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!