Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GetElementByID - Multiple IDs

doStuff(document.getElementById("myCircle1" "myCircle2" "myCircle3" "myCircle4")); 

This doesn't work, so do I need a comma or semi-colon to make this work?

like image 857
Maurice Tempelsman Avatar asked Jan 18 '13 22:01

Maurice Tempelsman


2 Answers

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")); 
like image 165
jfriend00 Avatar answered Sep 21 '22 12:09

jfriend00


This will not work, getElementById will query only one element by time.

You can use document.querySelectorAll("#myCircle1, #myCircle2") for querying more then one element.

ES6 or newer

With the new version of the JavaScript, you can also convert the results into an array to easily transverse it.

Example:

const elementsList = document.querySelectorAll("#myCircle1, #myCircle2"); const elementsArray = [...elementsList];  // Now you can use cool array prototypes elementsArray.forEach(element => {     console.log(element); }); 

How to query a list of IDs in ES6

Another easy way if you have an array of IDs is to use the language to build your query, example:

const ids = ['myCircle1', 'myCircle2', 'myCircle3']; const elements = document.querySelectorAll(ids.map(id => `#${id}`).join(', ')); 
like image 41
Gabriel Gartz Avatar answered Sep 22 '22 12:09

Gabriel Gartz