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".

2

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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...; 
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.