[javascript] 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?

This question is related to javascript arrays get element document

The answer is


As stated by jfriend00,

document.getElementById() only supports one name at a time and only returns a single node not an array of nodes.

However, here's some example code I created which you can give one or a comma separated list of id's. It will give you one or many elements in an array. If there are any errors, it will return an array with an Error as the only entry.

function safelyGetElementsByIds(ids){
    if(typeof ids !== 'string') return new Error('ids must be a comma seperated string of ids or a single id string');
    ids = ids.split(",");
    let elements = [];
    for(let i=0, len = ids.length; i<len; i++){
        const currId = ids[i];
        const currElement = (document.getElementById(currId) || new Error(currId + ' is not an HTML Element'));
        if(currElement instanceof Error) return [currElement];
        elements.push(currElement);
    };
    return elements;
}

safelyGetElementsByIds('realId1'); //returns [<HTML Element>]
safelyGetElementsByIds('fakeId1'); //returns [Error : fakeId1 is not an HTML Element]
safelyGetElementsByIds('realId1', 'realId2', 'realId3'); //returns [<HTML Element>,<HTML Element>,<HTML Element>]
safelyGetElementsByIds('realId1', 'realId2', 'fakeId3'); //returns [Error : fakeId3 is not an HTML Element]

document.getElementById() only takes one argument. You can give them a class name and use getElementsByClassName() .


getElementByID is exactly that - get an element by id.

Maybe you want to give those elements a circle class and getElementsByClassName


For me worked flawles something like this

doStuff(

    document.getElementById("myCircle1") ,

    document.getElementById("myCircle2") ,

    document.getElementById("myCircle3") ,

    document.getElementById("myCircle4")

);

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(', '));

The best way to do it, is to define a function, and pass it a parameter of the ID's name that you want to grab from the DOM, then every time you want to grab an ID and store it inside an array, then you can call the function

<p id="testing">Demo test!</p>

function grabbingId(element){
    var storeId = document.getElementById(element);

    return storeId;
}


grabbingId("testing").syle.color = "red";

I suggest using ES5 array methods:

["myCircle1","myCircle2","myCircle3","myCircle4"] // Array of IDs
.map(document.getElementById, document)           // Array of elements
.forEach(doStuff);

Then doStuff will be called once for each element, and will receive 3 arguments: the element, the index of the element inside the array of elements, and the array of elements.


You can use something like this whit array and for loop.

<p id='fisrt'>??????</p>
<p id='second'>??????</p>
<p id='third'>??????</p>
<p id='forth'>??????</p>
<p id='fifth'>??????</p>
<button id="change" onclick="changeColor()">color red</button>
<script>

    var ids = ['fisrt','second','third','forth','fifth'];

    function changeColor() {
        for (var i = 0; i < ids.length; i++) {
          document.getElementById(ids[i]).style.color='red';
 }
    }
</script>

Use jQuery or similar to get access to the collection of elements in only one sentence. Of course, you need to put something like this in your html's "head" section:

<script type='text/javascript' src='url/to/my/jquery.1.xx.yy.js' ...>

So here is the magic:

.- First of all let's supose that you have some divs with IDs as you wrote, i.e.,

 ...some html...
 <div id='MyCircle1'>some_inner_html_tags</div>
 ...more html...
 <div id='MyCircle2'>more_html_tags_here</div>
 ...blabla...
 <div id='MyCircleN'>more_and_more_tags_again</div>
 ...zzz...

.- With this 'spell' jQuery will return a collection of objects representing all div elements with IDs containing the entire string "myCircle" anywhere:

 $("div[id*='myCircle']")

This is all! Note that you get rid of details like the numeric suffix, that you can manipulate all the divs in a single sentence, animate them... Voilá!

 $("div[id*='myCircle']").addClass("myCircleDivClass").hide().fadeIn(1000);

Prove this in your browser's script console (press F12) right now!


Dunno if something like this works in js, in PHP and Python which i use quite often it is possible. Maybe just use for loop like:

function doStuff(){
    for(i=1; i<=4; i++){
        var i = document.getElementById("myCiricle"+i);
    }
}

Vulgo has the right idea on this thread. I believe his solution is the easiest of the bunch, although his answer could have been a little more in-depth. Here is something that worked for me. I have provided an example.

<h1 id="hello1">Hello World</h1>
<h2 id="hello2">Random</h2>
<button id="click">Click To Hide</button>

<script>

  document.getElementById('click').addEventListener('click', function(){
    doStuff();
  });

  function doStuff() {
    for(var i=1; i<=2; i++){
        var el = document.getElementById("hello" + i);
        el.style.display = 'none';
    }
  }

</script>

Obviously just change the integers in the for loop to account for however many elements you are targeting, which in this example was 2.


No, it won't work.

document.getElementById() method accepts only one argument.

However, you may always set classes to the elements and use getElementsByClassName() instead. Another option for modern browsers is to use querySelectorAll() method:

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

here is the solution

if (
  document.getElementById('73536573').value != '' &&
  document.getElementById('1081743273').value != '' &&
  document.getElementById('357118391').value != '' &&
  document.getElementById('1238321094').value != '' &&
  document.getElementById('1118122010').value != ''
  ) {
code
  }

You can do it with document.getElementByID Here is how.

function dostuff (var here) {
  if(add statment here) {
  document.getElementById('First ID'));
  document.getElementById('Second ID'));
  }
}

There you go! xD


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to get

Getting "TypeError: failed to fetch" when the request hasn't actually failed java, get set methods For Restful API, can GET method use json data? Swift GET request with parameters Sending a JSON to server and retrieving a JSON in return, without JQuery Retrofit and GET using parameters Correct way to pass multiple values for same parameter name in GET request How to download HTTP directory with all files and sub-directories as they appear on the online files/folders list? Curl and PHP - how can I pass a json through curl by PUT,POST,GET Making href (anchor tag) request POST instead of GET?

Examples related to element

How can I loop through enum values for display in radio buttons? How to count items in JSON data Access multiple elements of list knowing their index Getting Index of an item in an arraylist; Octave/Matlab: Adding new elements to a vector add item in array list of android GetElementByID - Multiple IDs Numpy ValueError: setting an array element with a sequence. This message may appear without the existing of a sequence? Check if one list contains element from the other How to get the focused element with jQuery?

Examples related to document

Selenium wait until document is ready GetElementByID - Multiple IDs Difference between $(document.body) and $('body') How do I convert a org.w3c.dom.Document object to a String? Convert Mongoose docs to json Create auto-numbering on images/figures in MS Word Accessing elements by type in javascript $(window).scrollTop() vs. $(document).scrollTop() Get IFrame's document, from JavaScript in main document "Access is denied" JavaScript error when trying to access the document object of a programmatically-created <iframe> (IE-only)