How can I tell if there are two divs with the same id in javascript?
I don't know what you are trying to achieve here, but usually you shouldn't have two elements with the same ID. But if you have a reason to do so, perhaps you are creating a validator or something like that, you can do the following to count the number of items
var count = document.querySelectorAll('#test').length;
console.log(count);
then you can skip them and remove them with
document.querySelectorAll('#test')[1].remove();
source to share
You need to loop through all the elements, as helpers like getElementById()
will not work well if they are not unique.
Example, no jQuery needed. A double identifier signifies.
var idMap = {};
var all = document.getElementsByTagName("*");
for (var i=0; i < all.length; i++) {
// Do something with the element here
var elem = all[i];
if(elem.id != ""){ //skip without id
if(idMap[elem.id]){
alert("'" + elem.id + "' is not unique")
}
idMap[elem.id] = true;
}
}
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title></title>
</head>
<body>
<div id="id1"></div>
<div id="id2"></div>
<div id="id3"></div>
<div id="id4"></div>
<div id="id5"></div>
<div id="id1"></div>
</body>
</html>
source to share
$('[id]').each(function(){
var ids = $('[id="'+this.id+'"]');
if (ids.length>1 && ids[0]==this){
$("#"+this.id).remove();
}
});
the above function uses jquery to create an array of all ids in the document and remove the duplicate id
source to share
Something like this should do what you want
$('[id]').each(function (i) {
$('[id="' + this.id + '"]').slice(1).remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id = "1">
ola
</div>
<div id = "2">
ole
</div>
<div id = "1">
ola
</div>
<div id = "3">
olo
</div>
<div id = "1">
ola
</div>
<div id = "3">
olo
</div>
Example based on link: jQuery: Find duplicate IDs and remove all but the first
source to share