Skip to content

Instantly share code, notes, and snippets.

@dmhendricks
Last active May 16, 2024 12:17
Show Gist options
  • Save dmhendricks/01e00354a802d11094a4bb7a54889bb2 to your computer and use it in GitHub Desktop.
Save dmhendricks/01e00354a802d11094a4bb7a54889bb2 to your computer and use it in GitHub Desktop.
Bind querySelector to dollar sign ($) to reference DOM elements without jQuery
/**
* Bind querySelector to dollar sign ($) to easily reference DOM elements without jQuery
* Source: https://twitter.com/MrAhmadAwais/status/1113094169025708033
*/
// In case you're also loading jQuery
jQuery.noConflict();
// Example - Change an element's background color
// Shorthand for: document.querySelector( '.selector' ).style.background = '#BADA55';
const $ = document.querySelector.bind( document );
$( '.selector' ).style.background = '#BADA55';
// Or wait for DOM
(function($) {
$( '#element' ).innerHTML = 'DOM is loaded!';
})( document.querySelector.bind( document ) );
@dmhendricks
Copy link
Author

awais-querySelector-bind

@sylbru
Copy link

sylbru commented Jul 13, 2023

In case anyone sees this: using this alias causes Cypress to hang and fail when using .invoke(…). Too bad I couldn’t find a way to make both work at the same time!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment