JavaScript function which takes multiple ids and returns multiple elements

Introduction

This tutorial shows how to implement a JavaScript function which takes multiple ids and returns multiple elements. document.getElementById() only supports one name at a time and returns a single node but not multiple nodes or an array of nodes.

You have several different options to implement such function, i.e., will take multiple ids and returns multiple elements:

  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.

Using document.querySelectorAll()

Using the document.querySelectorAll() you can pass multiple ids which can be used for your application requirements.

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

Using document.getElementsByClassName()

Using document.getElementsByClassName() you can pass same class name which is used for multiple elements on your web page.

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

Using Custom Function

You can also write your own custom function in JavaScript to get the multiple ids from your HTML page.

function getElementsByIds(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);
}

Now you can pass the above ids to a function to process for your business requirements.

someFunc(getElementsByIds("myCircle1 myCircle2 myCircle3 myCircle4"));

The someFunc() can be written something like below:

function someFunc(ids) {
    //do your logic
}

Thanks for reading.

Leave a Reply

Your email address will not be published. Required fields are marked *