why is the element not found using the queryselector method? Even though the element already exists in the DOM tree when searching for an element using the queryselector method, and the search itself using the queryselector method is located in the same function, where is this element created?
It can only be found in a search for the tag itself and not additionally with the attribute. I don’t understand it since the entire syntax is probably good?
function createElementLabel (container) {
let labelElement = document.createElement("label");
container.appendChild(labelElement);
labelElement.classList.add(generateLetters());
labelElement.style.display = "inline-block";
labelElement.style.fontSize = "15px";
labelElement.style.color = "rgb(141, 145, 145)";
labelElement.innerText = "this is an element";
console.warn(container.querySelector("LABEL")); //<--- Works
console.warn(container.querySelector('LABEL[innerText="this is an element"]')); //<--- Doesn't work
return labelElement;
>Solution :
The issue you have is with the attribute you’re trying to select. The querySelector method doesn’t recognize innerText as a valid attribute for selection. It’s a property of an element, but not an attribute that can be used in a CSS selector.If you want to select an element based on its text content, you’ll need to use a different approach, such as iterating over the elements and checking their innerText property.
Try using the code like this…
function findElementWithText(container, text) {
let labels = container.querySelectorAll("label");
for(let i = 0; i < labels.length; i++) {
if(labels[i].innerText === text) {
return labels[i];
}
}
return null;
}
console.warn(findElementWithText(container, "this is an element"));
enter code here