skip to Main Content

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 🙂

2

Answers


  1. Chosen as BEST ANSWER

    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
    

  2. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search