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 bee:
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 bee:
- 1 iterate all lis, use something like a set to track texts seen already, remove the li if text is already seen before. – Chris Li Commented Mar 5, 2020 at 20:11
- 4 Remove the id attributes from <li> elements, you can use the class attribute on them. Id's need to be unique. – Rumplin Commented Mar 5, 2020 at 20:13
- 3 Duplicate id and no ul elements, check html please. – estinamir Commented Mar 5, 2020 at 20:14
2 Answers
Reset to default 7You 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>
you can just iterate over the selected node list without much overhead using one loop, like this:
let elements = document.querySelectorAll("li");
textArr = [];
elements.forEach(function(d, i) {
if(textArr.indexOf(d.innerText) > -1) {
d.remove();
}
else {
textArr.push(d.innerText);
}
});
<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>
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744354870a4570181.html
评论列表(0条)