我的文档上有四个div,只要其中至少两个具有相同的文本内容,我就想执行一些代码。
我找不到一个不包括手动比较每个divs 文本内容与所有其他divs 文本内容的解决方案
while(div1.textContent === div2.textContent || div1.textContent === div3.textContent || ....)
有没有简单的方法可以做到这一点?
--编辑网页
<div class="container">
<h2>Answers</h2>
<div class="row">
<div class="col-md option" id="option1">
Answer
</div>
<div class="col-md option" id="option2">
Answer
</div>
<div class="col-md option" id="option3">
Answer
</div>
<div class="col-md option" id="option4">
Answer
</div>
</div>
</div>
将div 保存到唯一的集合中,然后创建其文本内容的Set
。如果Set
的大小小于集合的长度,则一定存在匹配的内容。
test("foo");
test("bar");
function test(cls) {
var divs = document.querySelectorAll(`.${cls}`);
var set = new Set(Array.from(divs, el => el.textContent));
if (set.size < divs.length) {
console.log(`'${cls}' found matching content`);
} else {
console.log(`'${cls}' did not find matching content`);
}
}
.foo, .bar {
display: inline-block;
}
.foo {
color: blue;
}
.bar {
color: red;
}
<div class="foo">1</div>
<div class="foo">2</div>
<div class="foo">3</div>
<div class="foo">1</div>
<hr>
<div class="bar">1</div>
<div class="bar">2</div>
<div class="bar">3</div>
<div class="bar">4</div>
您可以执行以下操作:
const textArray = Array.from(document.querySelectorAll('.option'), el => el.innerText);
for(let el of textArray) {
const filtered = textArray.filter(item => item === el);
if (filtered.length > 1) {
doSomething();
break; // can be removed if you want to do continue the loop
}
}
这是另一种类似于回调答案的方法。
选择所有元素及其文本内容。按是否存在 2 个或更多来过滤文本内容。
//select all elements, getting only their text content
let options = Array.from(document.getElementsByClassName("option")).map(function(options){
return options.textContent;
});
//filter by whether 2 or more exist
multipleOptions = options.filter((item, i)=>{
const iOf = options.indexOf(item);
return(iOf != i && iOf != -1);//if 2 or more of item, keep it
});
//output..
console.log("number of options with 2 or more of the same text content:", multipleOptions.length);
console.log("boolean, contains 2 or more of the same content?", multipleOptions.length > 0);
<div class="container">
<h2>Answers</h2>
<div class="row">
<div class="col-md option" id="option1">
Answer
</div>
<div class="col-md option" id="option2">
Answer
</div>
<div class="col-md option" id="option3">
test
</div>
<div class="col-md option" id="option4">
test
</div>
</div>
</div>