Skip to content
Advertisement

Proper way of writing $(this).text().match(r) into vanilla JS?

I have the following function written in jQuery which I would like to convert to javascript but I couldn’t find a proper way so far.

const word = document.getElementById("searchField").value;
        const r = new RegExp("(" + word + ")", "ig");
$(".list-item").each(function (i) {
            if ($(this).text().match(r)) {
                
            }
        });

I rewrote it this way:

const word = document.getElementById("searchField").value;
        const r = new RegExp("(" + word + ")", "ig");

        let pickComp = document.querySelectorAll('.list-item');
        Array.from(pickComp).forEach((i) => {
            if (//how can I rewrite the jQuery here?) {
                
            }
        })

Advertisement

Answer

const word = document.getElementById("searchField").value;
const r = new RegExp("(" + word + ")", "ig");

const pickComp = document.querySelectorAll('.list-item');

pickComp.forEach(item => {
      if (item.innerHTML.match(r)) {
        console.log("Match!!");
        }
      })
<p class="list-item">abc</p>
<p class="list-item">abc</p>
<p class="list-item">abc</p>
<p class="list-item">abc</p>
<input id="searchField" value="abc">
Advertisement