how to write a function for checking the presence of an element with a certain id.
I have these IDs for verification set in an array:
let CartArray = ["cart-0", "cart-1", "cart-2", "cart-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");
}
}
});
});
the code doesn’t fit in stackoverflow, so I’m adding a link to codepen:
https://codepen.io/SHvari_David_Simba/pen/JjBNXzp
I tried to check the presence of the item by the id from the array, but nothing happened
3
Answers
This might suit your need.
You can use
myelement.querySelector('[id="' + id + '"]')
to search children by id: