Issue
how to remove duplicate li in div using js?
<div id="tags">
<li id="tag">sport</li>
<li id="tag">news</li>
<li id="tag">sport</li>
<li id="tag">sport</li>
<li id="tag">cars</li>
</div>
must become:
Solution
You can do that in following steps:
- Select all the elements and create
Set
containing all the texts of<li>
- Then loop through elements list using
forEach
- Check if the
Set
doesn't contain theinnerHTML
of current element then remove the element - If set contains the text then don't remove the element but remove the text from
Set
Note: id
of element should be unique in the whole document. Two elements can't have same id
const tags = [...document.querySelectorAll('#tags > li')];
const texts = new Set(tags.map(x => x.innerHTML));
tags.forEach(tag => {
if(texts.has(tag.innerHTML)){
texts.delete(tag.innerHTML);
}
else{
tag.remove()
}
})
<div id="tags">
<li>sport</li>
<li>news</li>
<li>sport</li>
<li>sport</li>
<li>cars</li>
</div>
Answered By - Maheer Ali
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.