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

Use a predefined array of string values against querySelectorAll, to perform a specific action

If I have a predefined array of string values, how can I see if any of them exist in the DOM via querySelectorAll and textContent?


//my array of predefined string values
let primaries = ["house", "people", "cat", "dog"];

let mTable = document.querySelectorAll("#mytable td font");

this is where I am stuck…I want to find any string from primaries against mTable. And if any string value is found, then perform a specific action (i.e. console.log("I found you"));

This is what I have so far but it only works for one element at a time. How can I expand my thought process..

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

var mPrimary = Array.from(
  mtable.querySelectorAll("td font")
).find((el) => el.textContent === "house");
if (mPrimary) {
  mPrimary.closest("tr").classList.add("d-none");
}

>Solution :

Use the Array.includes() method to search for the text in the array.

And use .filter() instead of .find() to get all the matching td’s. Then you can use .forEach() to process all of them.

var mPrimary = Array.from(mtable.querySelectorAll("td font")
).filter(
  (el) => primaries.includes(el.textContent.trim())
);
mprimary.forEach(el => el.closest("tr").classList.add("d-none"));

I added .trim() so surrounding whitespace won’t cause the match to fail.

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