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:
- You could implement your own function that takes multiple ids and returns multiple elements.
- You could use
document.querySelectorAll()
that allows you to specify multiple ids in a CSS selector string . - 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>
How to call getElementById() on multiple ids
I doubt you really need all that... try this and see if it serves your need.
function minmax(inp_field) {
let val = parseFloat(inp_field.value),
min = parseFloat(inp_field.min),
max = parseFloat(inp_field.max);
//below we call a function that checks if the value contains any scientific/engineering notation
val = decimalCount(val)
if (val < min) {
inp_field.value = inp_field.min;
} else if (val > max) {
inp_field.value = inp_field.max;
} else {
inp_field.value = val;
}
}
function decimalCount(val){
let valStr = val.toString(); //convert float to string
//check if the value include e-... example 1e-7
if(valStr.includes('e-')){
//get the value before the scietific notation
let beforeE = valStr.substr(0,valStr.indexOf('e'));
//the following removes a comma. example 0.000000017 == 1.7e-7
beforeE = beforeE.replace('.','')
//get the number of zeros after the scientific notation
let decimalPlace = valStr.substr((valStr.indexOf('-') + 1)) - 1
//we set a variable for the zeros after the .
let zeros = '.';
//assign the zeros to appear after the .
for(let i=0;i<decimalPlace;i++){
zeros += 0;
}
//concatenate the results and return the value for display
return 0 + zeros + beforeE;
}else{
//else, we return the min/max as it is
return val;
}
}
<input id="input1" type="text" onchange="minmax(this)" min="0.01" max="94.99">
<input id="input2" type="text" onchange="minmax(this)" min="0.00000001" max="99.99">
<input id="input3" type="text" onchange="minmax(this)" min="5" max="25">
<input id="input4" type="text" onchange="minmax(this)" min="1" max="10">
How to Use document.getElementById with Multiple IDs in JavaScript?
Here's an approach, define a function addClickHandlers
which takes in an array of elements (each element has an id, icon and text) and then adds click handlers for each element.
const addClickHandlers = (ids) => {
ids.forEach(({ id, icon, text }) => {
const element = document.getElementById(id);
element.addEventListener("click", function handleClick() {
element.innerHTML = `<iconify-icon icon="${icon}"></iconify-icon> ${text}`;
});
});
};
addClickHandlers([
{ id: "copy_btn", icon: "akar-icons:copy", text: "Copied" },
{ id: "down_btn", icon: "ri:file-download-line", text: "Downloading" },
]);
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-gH2yIJqKdNHPEq0n4Mqa/HGKIhSkIHeL5AyhkYV8i59U5AR6csBvApHHNl/vI1Bx" crossorigin="anonymous"><script src="https://code.iconify.design/iconify-icon/1.0.0/iconify-icon.min.js"></script><button type="button" class="btn btn-dark" id="down_btn"><iconify-icon icon="ri:file-download-line"></iconify-icon> Download</button><button type="button" class="btn btn-dark" onclick="copyEvent();" id="copy_btn"><iconify-icon icon="akar-icons:copy"></iconify-icon> Copy </button>
Add multiple ids in getElementById
You can use querySelectorAll
to select many items by their IDs:
var items = document.querySelectorAll('#id2, #id3, #id5');
for (var i = 0; i < items.length; i++){ items[i].onclick = function() { this.innerText = this.innerText + '!'; };}
2, 3, 5 are working:
<p id="id1">I am 1</p><p id="id2">I am 2</p><p id="id3">I am 3</p><p id="id4">I am 4</p><p id="id5">I am 5</p>
How can i get multiple ids getElementById
Using jQuery:
$('#id1, #id2').on('keypress', function(e) {
var chr = String.fromCharCode(e.which);
if ("><abc/\"".indexOf(chr) >= 0)
return false;
});
You can expand the list of id selectors: "#id1, #id2, #id3, ...
".
But if there are too many elements, it's better to assign them a class and target them like this:
$('.className').on('keypress', function(e) {
var chr = String.fromCharCode(e.which);
if ("><abc/\"".indexOf(chr) >= 0)
return false;
});
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
Related Topics
Multiple, Sequential Fetch() Promise
How to Convert Special Utf-8 Chars to Their Iso-8859-1 Equivalent Using JavaScript
Preloader Wont Ignore Websocket - Pace Js
How to Display PDF (Blob) on iOS Sent from My Angularjs App
How to Run JavaScript Inside Swift Code
Filter Array of Objects by Multiple Properties and Values
Adding/Removing Items from a JavaScript Object with Jquery
How to Render a Partial from JavaScript
What Is an Exclamation Point in JavaScript
Is There a Jquery Autogrow Plugin for Text Fields
Decryption of Aes Created with Sjcl.Js in Ruby
Inline Ruby in :JavaScript Haml Tag