1

So I have a file like

<div class="u1">

<p id="level1"></p>
<p id="level2"></p>

</div>

<div class="u2">

<p id="level1"></p>
<p id="level3"></p>

</div>

and if I use something like

document.getElementbyId("level1").innerText(or innerHtml) = "Hello"

it writes that string on one element, and not on every element with id="level1"

I tried with

$('#level1').text("Hello");

but it works only for one.

I need something to write a string on every element with id="level1".

SeverityOne
  • 2,476
  • 12
  • 25
JvstAlf
  • 83
  • 1
  • 9
  • Use `class` instead of `id` – Vinie Mar 18 '21 at 11:27
  • Does this answer your question? [Can multiple different HTML elements have the same ID if they're different elements?](https://stackoverflow.com/questions/5611963/can-multiple-different-html-elements-have-the-same-id-if-theyre-different-eleme) – user3840170 Mar 18 '21 at 11:37

3 Answers3

1
  1. ID is a unique identifier, so you can't have few items with the same ID. Provided HTML code is invalid. You can use CLASS attribute or data-id or....

  2. If you can't change HTML and it comes from third-party dependency, then we have a list of NOT recommended but WORKING solutions

jQuery: $('[id="level1"]').text("Hello");

js: var elements = document.querySelectorAll('#level1'); + for loop to iterate elements

And a lot of similar solutions based on knowledges how elements selecting works under the hood

Alex
  • 131
  • 7
0

It is ideal to have Unique Ids and thus you cannot update it this way. What you can do is you can give it a class like this:

<div class="u1">

<p id="level1" class="helloText"></p>
<p id="level2"></p>

</div>

<div class="u2">

<p id="level1" class="helloText"></p>
<p id="level3"></p>

</div>

Now use this JS to update the HTML:

var paras = document.getElementsByClassName("helloText");
for (i = 0; i < paras.length; i++) {
  paras[i].innerHTML = "Hello";
}

You can also remove the Ids or make them unique to make your code cleaner. It is never recommended to use duplicate Ids.

Charu
  • 40
  • 4
0

You give a classname to the elements you need:

class = "levels"

in the script, use document.getElementsByClassName, which return an array with all elements. then you can loop through that array to get the info of each elements.

let levels = document.getElementsByClassName("levels");
for (let j=0; j<levels.length; j++){
 levels[j] do something...; 
}
weix
  • 1
  • 5