0

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.

sangoko
  • 331
  • 1
  • 13

3 Answers3

1

I would send you to this page: JavaScript case insensitive string comparison

In brief, you can simply compare the upper (or lower versions) of two strings to check if they are ignoreCaseEqual, by using toUpperCase() or toLowerCase() function as explained below:

string1.toUpperCase() === string2.toUpperCase();
string1.toLowerCase() === string2.toLowerCase();

In your case just use:

if (link.textContent.toLowerCase() == 'remove') { 
    // since remove is already lowercase
    // do stuff
}
saniales
  • 451
  • 3
  • 14
0

You can use javscript function to change the text to lowercase. in this i just create a variable name text and then use toLowerCase() function in if condition. Thanks

 var text = link.textContent;
 if (text.toLowerCase() == 'remove') {
     text.click();
 }

EDIT: code indented

Haq Nawaz
  • 412
  • 1
  • 4
  • 12
0

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.

Víctor
  • 112
  • 5