How To Work With jQuery Multiple Elements With Same Id

Hello Friends, In this post I wil explain how to Work with jQuery multiple elements with same id. In simple way if you use id to select all div having same ids then it will select first id only but if you want to select ,want go through each div or any other element with same id then I will explain you how you can do that.

So we will take simple example in which there are six div tags three div have id ‘red’ and other three have id ‘green’, on page load we will simple make background color red for id ‘red’ divs and green for id ‘green’. So below is html :

<div id="red">1</div>
<div id="green">2</div>
<div id="red">3</div>
<div id="green">4</div>
<div id="red">5</div>
<div id="green">6</div>

Now below is jQuery code :

$(function() {
 $('[id="red"]').css('background-color', 'red');
 $('[id="green"]').css('background-color', 'green');
});

So above code will make all red id div to red and green id div to green color. We have used attribute here by using id to go through each id. Usually we use simple ‘#’ with id like this :

$(function() {
 $('#red').css('background-color', 'red');
 $('#green').css('background-color', 'green');
});

mostly we use above code but above code only make first div red and first div green and dont do anything with other elements, So to go through each element with same id we can use attribute as I shown in second code.

Usually in html there shouldn’t be multiple elements with same id but if you got any case in which you have multiple elements with same id you can use this code it will work smoothly.

Below is jsfiddle in which you can see live preview of above code :

I hope this code will help you. If you have any thoughts or suggestion you can post them in comments.

Subscribe to PHP Freelancer

Enter your email address: