How to use $ as jQuery-like selector?

<!DOCTYPE html>
<html>
  <body>
    <input id="awesomeInput" value="2" />
    
    <script>
      window.$ = document.querySelector.bind(document);
      window.$$ = document.querySelectorAll.bind(document);
      
      setTimeout(() => {
        let awesomeInput = $('#awesomeInput');
        awesomeInput.value = 10;
      }, 5000);
    </script>
  </body>
</html>
Copy

July 26th, 2020

# Select elements the jQuery-way without jQuery

Add to bookmarks

We created a new $and $$ function on the window object via bind(). This way our newly created functions will be the shortcuts for the querySelector and querySelectorAll method.

The example updates the value of the input from 2 to 10 after 5000 ms by using our jQuery-like selector.

HomeBookmarks