Maurice Tempelsman
Maurice Tempelsman

Reputation: 953

Can I use document.getElementById() with 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?

Upvotes: 48

Views: 300478

Answers (19)

user1182625
user1182625

Reputation: 169

There was a time when you could do exactly that.

20+ years ago, you could get all elements with the same ID with document.getElementById.

Upvotes: 0

Kanauer
Kanauer

Reputation: 1

This is doable without jQuery and just need a querySelect, that looks somthing like this:

document.querySelectorAll('[id^="myCircle"]')

you dont need the number on the end. This fill search for all matching IDs.

The same is doable with jQuery as follows

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

I would recommend you the first version.

Upvotes: 0

code xxii
code xxii

Reputation: 1

I needed something similar, and used this:

<script>
  function copyClipboard(target) {
    var copyText = document.getElementById(target).innerHTML;
    navigator.clipboard.writeText(copyText);
   } 
</script>

//html
<button onclick="copyClipboard(getAttribute('id'))" id="grav">123

This way I could obtain the object id in short code.

Upvotes: 0

Michel Rummens
Michel Rummens

Reputation: 692

If, like me, you want to create an or-like construction, where either of the elements is available on the page, you could use querySelector. querySelector tries locating the first id in the list, and if it can't be found continues to the next until it finds an element.

The difference with querySelectorAll is that it only finds a single element, so looping is not necessary.

document.querySelector('#myCircle1, #myCircle2, #myCircle3, #myCircle4');

Upvotes: 1

Ahmad Saeed
Ahmad Saeed

Reputation: 163

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
  }

Upvotes: -1

Plinderman
Plinderman

Reputation: 26

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]

Upvotes: 0

Samir Vukasinovic
Samir Vukasinovic

Reputation: 11

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>

Upvotes: 1

Gabriel Gartz
Gabriel Gartz

Reputation: 2870

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

Upvotes: 21

accimeesterlin
accimeesterlin

Reputation: 4718

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

Upvotes: 1

Dan Zuzevich
Dan Zuzevich

Reputation: 3831

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.

Upvotes: 1

An Capone
An Capone

Reputation: 131

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

Upvotes: 1

Oriol
Oriol

Reputation: 288030

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.

Upvotes: 3

user4145839
user4145839

Reputation: 7

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

Upvotes: -5

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!

Upvotes: 0

Nicola Mihaita
Nicola Mihaita

Reputation: 71

For me worked flawles something like this

doStuff(

    document.getElementById("myCircle1") ,

    document.getElementById("myCircle2") ,

    document.getElementById("myCircle3") ,

    document.getElementById("myCircle4")

);

Upvotes: 0

jfriend00
jfriend00

Reputation: 707218

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"));

Upvotes: 88

Muhammad Hani
Muhammad Hani

Reputation: 8664

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

Upvotes: 1

sachleen
sachleen

Reputation: 31131

getElementByID is exactly that - get an element by id.

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

Upvotes: 1

VisioN
VisioN

Reputation: 145388

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");

Upvotes: 10

Related Questions