Search code examples
javascriptarraysdom

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..

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.