Skip to content

Instantly share code, notes, and snippets.

@jhkueh
Last active September 16, 2017 10:02
Show Gist options
  • Save jhkueh/81b54ca175ff74b3af5b9be9a22526d9 to your computer and use it in GitHub Desktop.
Save jhkueh/81b54ca175ff74b3af5b9be9a22526d9 to your computer and use it in GitHub Desktop.
Use document.querySelector() instead of document.getElementById() or document.getElementsByClassName()

Web browsers now support jQuery-like query selectors using document.querySelector().


For the jQuery code $('.sample#test'), the conventional vanilla JS way to do it might be:

var divById = document.getElementById('#test');

// or

var divByClass = document.getElementsByClassName('.sample')[0];

Instead, there is now a more eloquent way:

var div = document.querySelector('.sample#test');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment