Javascript and Getelementbyid for Multiple Elements With the Same Id

Get multiple elements by Id

If you can change the markup, you might want to use class instead.

HTML

<a class="test" name="Name 1"></a>
<a class="test" name="Name 2"></a>
<a class="test" name="Name 3"></a>

JS

var elements = document.getElementsByClassName("test");
var names = '';
for(var i = 0; i < elements.length; i++) {
names += elements[i].name;
}
document.write(names);

jsfiddle demo

More same id´s in document.getElementById("")

instead of id you might want to use some other attribute. a class common on all HTML element will be a good idea. If your markup is something like below

<div class="name abc"></div>
<div class="name xyz"></div>
<div class="name pqr"></div>
<div class="name hjk"></div>

then you can write javascript code to set display:block for all of them as shown below

var elements = document.getElementsByClassName("name");
if (elements != null) {
for (var i = 0; i < elements.length; i++) {
if (elements[i].style.display === "block") {
elements[i].style.display = "none";
} else {
elements[i].style.display = "block";
}
}
}

Note: In HTML it is not valid to have same id for multiple DOM elements

EDIT: added if check in loop to allow toggle

Dealing with Two Elements with same ID in JavaScript

I know that IDs should be unique, however, I have to deal with a page
that has two elements with the exact same ID

As you've stated it should be unique hence if you have more than one id attribute with the same name then that's not valid HTML.

How can I access the second element with the exact same ID as the
first in JavaScript?

wouldn't it be easier to use getElementsByClassName since having two id attributes with the same name is invalid HTML?.

with that in mind, you can use getElementsByClassName.That may be more suited to your requirements.

Example:

var x = document.getElementsByClassName("Design_01"); // x is an array
var firstElement = x[0]; // get first element
var secondElement = x[1]; // get second element

Relevant Readings:

  • HTML DOM getElementsByClassName() Method
  • JavaScript Arrays

Changing multiple elements with same id

Instead of selecting the element with $('#my-id'), you could use $('[id="my-id"]') to select all of them.

However, as all the comments mention you should really switch to classes. ID's are not meant to be used more than once on a page.

Two elements with same ID- trying to figure out what I can change

You should not use numerical id, id should start with an letter

You can use querySelector() to get input value:

const val = document.querySelector('[id="' + hour + '"] .hourinput').value;

GetElementByID - Multiple IDs

document.getElementById() only supports one name at a time and only returns a single node not an array of nodes. You have several different options:

  1. You could implement your own function that takes multiple ids and returns multiple elements.
  2. You could use document.querySelectorAll() that allows you to specify multiple ids in a CSS selector string .
  3. You could put a common class names on all those nodes and use document.getElementsByClassName() with a single class name.

Examples of each option:

doStuff(document.querySelectorAll("#myCircle1, #myCircle2, #myCircle3, #myCircle4"));

or:

// put a common class on each object
doStuff(document.getElementsByClassName("circles"));

or:

function getElementsById(ids) {
var idList = ids.split(" ");
var results = [], item;
for (var i = 0; i < idList.length; i++) {
item = document.getElementById(idList[i]);
if (item) {
results.push(item);
}
}
return(results);
}

doStuff(getElementsById("myCircle1 myCircle2 myCircle3 myCircle4"));

How can I pass multiple ids in getElementById

You can use querySelectorAll and then attach click events to all divs with id matching active_*. In the click event, you can use the split method to extract the number part and then use to access your dom elements.

let elements = document.querySelectorAll("[id^='active_']");
for (const element of elements) { element.addEventListener('click', function(event) { let index = this.id.split('_')[1]; console.log(`gender_${index}`, `size_${index}`, `q_${index}`); });}
div {  margin-bottom: 1em;}
<div id='active_0'>a</div><div id='active_1'>b</div><div id='active_2'>c</div><div id='active_3'>d</div>

Geting reference to many elements having the same id using Javascript

You can get all the divs like this

var alDivs = document.getElementById("element").parentNode.getElementsByTagName("div");


Related Topics



Leave a reply



Submit