Home > Mobile >  Match split words from input field with JS
Match split words from input field with JS

Time:02-10

I have an input field value that gets split.

<input type="text" id="findW" value="command prompt" />

const txtValue = document
  .getElementById("findW")
  .value.replace(/[.* ?^${ }()|[\]\\]/g, "\\$&");

const r2 = txtValue.split(" ");
console.log(`R2 with split looks like: ${r2}`);

Every word resulted from splitting must be checked if appears in some elements in order to display them. I did it using jQuery but I would like to use vanilla JS.

let searchInElements = `.some-classes-to-search`;

//How can be rewritten in JS this jQuery below?
$(searchInElements).each(function (i, el) {
  if ($(this).text().match(r2)) {
    showElement(el);
  }
});

Function used to display elements with the words from input:

function showElement(el) {
  el.closest("#idOfEl")
    ? (el.closest("#idOfEl").style.display = "block")
    : null;
}

CodePudding user response:

It's not all that different really.

let searchInElements = `.some-classes-to-search`;

// Vanilla
document.querySelectorAll(searchInElements).forEach(el => {
  if (el.innerText.trim().match(r2)) showElement(el);
})

function showElement(el) {
  if (parent = el.closest("#idOfEl")) parent.style.display = "block";
}
  • Related