- 此问题在此处已有答案**:
Is there an "exists" function for jQuery?(47个答案)
20小时前关门了。
如何编写一个函数来检查某个id的元素是否存在。我在一个数组中设置了这些id来进行验证:令车数组=["车-0","车-1","车-2","车-3"];
JavaScript语言:
//=== === === Cart === === ===\\
$(document).ready(function() {
//========= checking the presence of items in the cart when the page is loaded =========\\
if(document.getElementById('myDIV').childElementCount == 0) {
document.getElementById('myDIV').innerHTML = "cart is empty";
}
const element = document.getElementById('myDIV');
const numberOfChildren = element.childElementCount; //====== Number of items in the cart
//========= Changing ::before for the cart when the page is loaded =========\\
for(var i = 0; i < numberOfChildren; i++) {
CartCount++;
}
document.getElementById("CountCartS").setAttribute('CartCountS', CartCount);
//========= Add to cart (number changes) =========\\
$("#button-count").click(function () {
CartCount++;
document.getElementById("CountCartS").setAttribute('CartCountS', CartCount);
});
const button = document.querySelector('#button');
button.addEventListener('click', function() {
for(var i = 0; i < numberOfChildren; i++) {
const parent = document.getElementById('myDIV');
const child = parent.children[i];
if(parent.childElementCount > 0) {
if(child.id == CartArray[i]) {
alert(child.id + " --- there is a div with this id");
}
else if(child.id != CartArray[i]) {
alert(child.id + " --- does not have a div with that id");
}
}
else if(parent.childElementCount == 0) {
document.getElementById('myDIV').innerHTML = "cart is empty";
}
else {
alert("Error");
}
}
});
});
代码不适合stackoverflow,所以我添加了一个到codepen的链接:https://codepen.io/SHvari_David_Simba/pen/JjBNXzp
我尝试通过数组中的id检查该项是否存在,但没有任何结果
3条答案
按热度按时间mgdq6dx11#
您可以使用
myelement.querySelector('[id="' + id + '"]')
按id搜索子项:4jb9z9bj2#
这可能适合你的需要。
myzjeezk3#