Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why am I having trouble finding an item?

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;

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading