我需要找到当前页面上的所有重复项,计算它们并列出有多少重复项。到目前为止我有这段代码,但它只显示页面上有多少元素。我做错了什么?
我正在获取 div 元素,我正在尝试列出哪些 div 元素是重复的,重复了多少次并显示整个代码结构 <div>text<span>text</span></div>
重复元素可以是这样的:
<div>this is the <span>text</span> with <strong>something</strong></div>
我需要查找整个 div 元素 是否在页面上不止一次出现,并像这样制作列表:
<div>this is the <span>text</span> with <strong>something</strong></div> - count(2)
到目前为止的代码:
let htmlCollectionArray = document.getElementsByClassName('sql-hl-main')
let count = {}
Array.prototype.forEach.call(htmlCollectionArray, function(el, i) {
count[el] = (count[el]||0) + 1;
});
最佳答案
您可以使用 document.querySelectorAll()
获取类名 (.sql-hl-main div
) 下的所有 div 元素,并返回静态 NodeList .用 NodeList.forEach()
迭代 NodeList并使用元素的 outerHTML
字符串作为键:
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>
关于JavaScript - 查找所有具有类的元素,查找重复项并显示它们,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59275955/