Sasha
Sasha

Reputation: 8705

JavaScript - find all elements with class, find duplicates and show them

I need to find all duplicates on the current page, count them and make a list which how many duplicates are there. So far I have this code, but it is only showing how many elements are on the page. What am I doing wrong?

I am getting div elements, and I am trying to make a list which div elements are duplicated, how many times and to show whole code structure <div>text<span>text</span></div>

The duplicate element can be something like this:

<div>this is the <span>text</span> with <strong>something</strong></div>

I need to find if this whole div element is on the page more than once, and make list like this:

<div>this is the <span>text</span> with <strong>something</strong></div> - count(2)

Code so far:

let htmlCollectionArray = document.getElementsByClassName('sql-hl-main')
let  count = {}

Array.prototype.forEach.call(htmlCollectionArray, function(el, i) { 
    count[el] = (count[el]||0) + 1;
});

Upvotes: 1

Views: 445

Answers (2)

Ori Drori
Ori Drori

Reputation: 192317

You can use document.querySelectorAll() to get all div elements under a class name (.sql-hl-main div), and it returns a static NodeList. Iterate the NodeList with NodeList.forEach() and use the elements' outerHTML string as the key:

const count = {};
document.querySelectorAll('.sql-hl-main div')
  .forEach(el => {
    const key = el.outerHTML; // or innerHTML if you don't want the container div
    count[key] = (count[key] || 0) + 1;
  });

console.log(count)
<div class="sql-hl-main">
  <div>this is the <span>text</span> with <strong>something</strong></div>
  <div>text<span>text</span></div>
  <div>this is the <span>text</span> with <strong>something</strong></div>
  <div>this is the <span>text</span> with <strong>something</strong></div>
</div>

Upvotes: 2

symlink
symlink

Reputation: 12218

Why not just use the length property?

console.log(document.getElementsByClassName('sql-hl-main').length);
console.log(document.getElementsByClassName('sql-h3-main').length);
<div class="sql-hl-main"></div>
<div class="sql-hl-main"></div>
<div class="sql-hl-main"></div>
<div class="sql-hl-main"></div>
<div class="sql-hl-main"></div>
<div class="sql-hl-main"></div>
<div class="sql-hl-main"></div>
<div class="sql-hl-main"></div>
<div class="sql-hl-main"></div>
<div class="sql-h3-main"></div>
<div class="sql-h3-main"></div>

Upvotes: 0

Related Questions