0

I have a working function that looks for characters typed into an input field and adds a span element with a highlight class on it.

ATM I am trying to rewrite the the jQuery parts of the function into Vanilla JS, and I am running in to some issues. For example I have tried to replace the following $('.search-suggest__list--categories .search-suggest__highlight') with a vanilla JS querySelector like this: document.querySelector('.search-suggest__list--categories .search-suggest__highlight');, but then when I run the code I get .each() is not a function returned.

I also have issues understanding what $(this).html would equal in Vanilla JS.

Here is my function:

var search_value = document.getElementsByClassName('js-search-suggest-input')[0].value;

if(search_value.length !== 0){
    $('.search-suggest__list--categories .search-suggest__highlight').each(function(){
        var search_regexp = new RegExp(search_value, "g");
        $(this).html($(this).html().replace(search_regexp,"<span class='highlight'>"+search_value+"</span>"));
    });
}
Mikkel Fennefoss
  • 857
  • 1
  • 9
  • 32

1 Answers1

0
  1. Use querySelectorAll to get all elements with provided selector.
  2. Loop through them using forEach - each is jQuery function, forEach is in NodeList.prototype
  3. this.innerHTML is equivalent of $(this).html(). - innerHTML read

This should be enough for you to complete the task.

Tomasz Bubała
  • 2,093
  • 1
  • 11
  • 18