An array contains elements with duplicate id
<div data-id='48444884'>MM</div>
<div data-id='11101100'>LL</div>
<div data-id='72277727'>TT</div>
<div data-id='72277727'>TT</div>
<div data-id='48444884'>MM</div>
<div data-id='11101100'>LL</div>
<div data-id='72277727'>TT</div>
Can someone please tell me the best way to hide the duplicates div
I tried to do it:
- set "display: none;" to hide all div elements
- create array with a unique id
- set "display: block" for each element in with unique IDs
I know how to create an array with unique IDs through a new Set().map method:
const uniqId = new Set([...document.querySelectorAll('[data-id]')].map(id => id.dataset.id));
or by arr.filter:
let ids = Array.from(document.querySelectorAll('[data-id]'), id => id.dataset.id);
let uniqeid = ids.filter((element, index) => {
return ids.indexOf(element) === index;
});
console.log('UNIQE ID:', uniqeid);
But I don't really understand how to change style or add class to each element in array through id
Can someone please explain to me the correct way to do this
CodePudding user response:
At first select first element having the data-id
of uniqeid then change style
let ids = Array.from(document.querySelectorAll('[data-id]'), id => id.dataset.id);
let uniqeid = ids.filter((element, index) => {
return ids.indexOf(element) === index;
});
console.log('UNIQE ID:', uniqeid);
uniqeid.forEach(id=> {
document.querySelector(`[data-id="${id}"]`).style.display = "block";
});
<div data-id='48444884' style="display: none;">MM</div>
<div data-id='11101100' style="display: none;">LL</div>
<div data-id='72277727' style="display: none;">TT</div>
<div data-id='72277727' style="display: none;">TT</div>
<div data-id='48444884' style="display: none;">MM</div>
<div data-id='11101100' style="display: none;">LL</div>
<div data-id='72277727' style="display: none;">TT</div>
CodePudding user response:
Another way would be to use an array storing all used ids while iterating through all elements.
If the id of the current element was not already used, you would push this id to the array and just proceed.
If the id was already found, just hide the element with display: none
// Here we will store all already used ids, so we know, if any other element, with the same id should be hidden
const usedId = [];
// We just iterate through all elements with a data attribute of id
document.querySelectorAll('[data-id]').forEach(element => {
// We check if its own id is already used, if so, we hide this element.
// Else we just add the id to the array, so any other element with the same id will be hidden.
if(usedId.indexOf(element.dataset.id) === -1){
usedId.push(element.dataset.id);
}else{
element.style.display = "none";
}
})
<div data-id='48444884'>MM</div>
<div data-id='11101100'>LL</div>
<div data-id='72277727'>TT</div>
<div data-id='72277727'>TT</div>
<div data-id='48444884'>MM</div>
<div data-id='11101100'>LL</div>
<div data-id='72277727'>TT</div>