html - remove duplicate elements through javascript - Stack Overflow

how to remove duplicate li in div using js?<div id="tags"><li id="tag"&g

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:

  • sport
  • news
  • cars
  • 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:

  • sport
  • news
  • cars
  • Share Improve this question asked Mar 5, 2020 at 20:09 Fox MaidenFox Maiden 431 silver badge5 bronze badges 3
    • 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
    Add a ment  | 

    2 Answers 2

    Reset to default 7

    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 the innerHTML 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条)

    • 暂无评论

    联系我们

    400-800-8888

    在线咨询: QQ交谈

    邮件:admin@example.com

    工作时间:周一至周五,9:30-18:30,节假日休息

    关注微信