JavaScript - 查找所有具有类的元素,查找重复项并显示它们

标签 javascript arrays

我需要找到当前页面上的所有重复项,计算它们并列出有多少重复项。到目前为止我有这段代码,但它只显示页面上有多少元素。我做错了什么?

我正在获取 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/

相关文章:

javascript - 预期的表达,得到 '}' ?

将二叉树转换为c中的数组

c# - 如何使用数组排序 linq 结果?

javascript - 在数组 javascript (ES5) 中添加相似对象的数量

javascript - 拆分后数组中存在制表符

javascript - 登陆页面上的 Mixpanel 集成不起作用

javascript - Nodejs : Can not read property of null

javascript - 图片链接与javascript

javascript - 全部勾选触发点击或改变参数

python - 如何用另一个数组中唯一值的索引替换 numpy 数组中的重复值?