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

Match split words from input field with JS

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:

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

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

>Solution :

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";
}
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