Search code examples
javascriptregexdomhtmlcase-sensitive

case insensitive textContent in Javascript


I have the following code that uses me to do stuff with all links with a certain textContent in a webpage:

let links = document.querySelectorAll('a b');
    for (let i = 0; i < links.length; i++) {
        let link = links[i];
        if (link.textContent == 'remove') {
        link.click();
        }
    }

In a certain webpage the links where named 'remove' on the webpage but appeared as 'Remove' (not the capitalized R) in DOM.

At the start I didn't know it is the case with the DOM and didn't understand why the code didn't work.

Gladly, I had the feeling it is in different in the DOM and indeed I saw I was right and when I changed it in the code from if (link.textContent == 'remove') to if (link.textContent == 'Remove'), the code worked.


As a beginner I ask only out of curiosity (because I'm humbly aware that such webpage-DOM discrepancies can occur):

Is there a way to make the textContent check to be case insensitive in vanilla JS?

I believe the answer would include regex but I've to take any regex course (should happen soon) and at the moment, cannot answer it myself.


Solution

  • Why don't you use toLowerCase function?

    let links = document.querySelectorAll('a b');
    for (let i = 0; i < links.length; i++) {
        let link = links[i];
        if (link.textContent.toLowerCase() == 'remove') {
        link.click();
        }
    }
    

    It wouldn't matter if it compares remove, Remove or even REMOVE.