Home > Blockchain >  :contains() function to vanilla JS
:contains() function to vanilla JS

Time:11-09

Good morning community! i need to transform this jquery code to vanilla JS, In this case it uses: => :contains()

this is the code in jquery

var hoveredProjectActive = $(
    "#cursor-outer .project__caption:contains('"   hoveredProject   "')"
);

This is the code i made in vanilla JS, i made a function to get that .textContent inside some selector, with no success..

function contains(selector, text) {
        var elements = document.querySelectorAll(selector);
        return [].filter.call(elements, function(element){
          return RegExp(text).test(element.textContent);
        });
      }

      const hoveredProjectActive = contains("#cursor-outer .project__caption", `${hoveredProject}`);

Is anyone able to help me to transform this code, thanks in advance :)

CodePudding user response:

Finally i was passing variable incorrectly, just change on my initial function the way i pass a variable to function

From: (cause it is already an string)

`${hoveredProject}`

to:

hoveredProject

CodePudding user response:

You could try using .includes instead of a regex

function contains(selector, text) {
    var elements = document.querySelectorAll(selector);
    return [].filter.call(elements, function(element){
        return element.textContent.includes(text);
    });
}

But if you're deadset on using a regex then try this:

return (new RegExp(text)).test(element.textContent);

Note how the RegExp class constructor is wrapped in () and is prefixed with new

  • Related