We can use jQuery to select multiple ids very easily by using the jQuery id selector on multiple ids.
$("#id1, #id2, #id3").attr("required",true);
Let’s see an example of this.
Let’s say we have the following HTML:
This is an empty div
This is an empty div
This is an empty div
This is an empty div
This is an empty div
This is an empty div
Say we wanted to change the background color of div’s 1, 4, and 5. We can do this by using jQuery to select the ids of those divs and then change the background color using the css() method.
Here is the jQuery code to select multiple ids:
$("#div1, #div4, #div5").css("background","green");
If you are using WordPress, don’t forget to change the $ to jQuery as below:
jQuery("#div1, #div4, #div5").css("background","green");
Using jQuery to Select Multiple Ids With a Click
In this example, we will have multiple divs with different ids. Each div will be a box with a white background and a black border. We will let the user click a button that will then change a random number of box background colors to green.
Here is the HTML setup:
Change random boxes
In the JavaScript part of this example, we will generate a random number between 1 and 16 (16 being the max number of boxes we have).
We will then change the background colors of the boxes whose id numbers match the numbers we randomly selected, to a greenish color.
We will use our code above to select all of the ids for the boxes at once, and change all the background colors of those boxes at once.
Finally, we will let the user know how many boxes we have changed using the html() method.
Here is the code:
$("#click-me").click(function(){
//First reset all background colors to white
$(".box").css("background","#fff");
//Generate random numbers from 1-16
var randomNum = Math.round(Math.random() * 15) +1;
//Loop through all elements of the array
var stringIds = "";
var numbers = [];
for( var i = 0; i < randomNum; i++ ){
//Generate a random number that will be the id for a box
var idNum = Math.round((Math.random() * 15)+1);
if( numbers.indexOf(idNum) == -1 ){
//Add number to our array
numbers.push(idNum);
if ( i == 0 ){
stringIds += "#box" + idNum;
} else {
//If it is not the first time in the loop, the code below will be slightly different
stringIds += ", #box" + idNum;
}
}
}
//Now that we have a string with all of our ids, we can change the bg color of them
$(stringIds).css("background","#7bbfa2");
//Let the user know how many boxes were changed
if( numbers.length == 1 ){
$("#results").html("Div " + stringIds + " was changed!");
} else {
$("#results").html("Divs " + stringIds + " were changed!");
}
});
The final code and output for this example is below.
Code Output:
Full Code:
Change random boxes
Hopefully this article has been useful to help you understand how to use the jQuery to select multiple ids.