A JavaScript function that returns the first element within the document (using depth-first pre-order traversal of the document's nodes) that matches the specified group of selectors.


element = document.querySelector(selectors);


  • element is an element object.
  • selectors is a string containing one or more CSS selectors separated by commas.


In this example, the first element in the document with the class "myclass" is returned:

var el = document.querySelector(".myclass");


Returns null if no matches are found; otherwise, it returns the first matching element.

If the selector matches an ID and this ID is erroneously used several times in the document, it returns the first matching element.

Throws a SYNTAX_ERR exception if the specified group of selectors is invalid.

querySelector() was introduced in the Selectors API.

The string argument pass to querySelector must follow the CSS syntax.

CSS Pseudo-classes will never return any elements, as specified in the Selectors API

To match ID or selectors that do not follow the CSS syntax (by using a colon or space inappropriately for example), you must escape the character with a back slash. As the backslash is an escape character in JavaScript, if you are entering a literal string, you must escape it twice (once for the JavaScript string, and another time for querySelector):

<div id="foo\bar"></div>
<div id="foo:bar"></div>

  console.log('#foo\bar')               // "#fooar"
  document.querySelector('#foo\bar')    // Does not match anything

  console.log('#foo\\bar')              // "#foo\bar"
  console.log('#foo\\\\bar')            // "#foo\\bar"
  document.querySelector('#foo\\\\bar') // Match the first div

  document.querySelector('#foo:bar')    // Does not match anything
  document.querySelector('#foo\\:bar')  // Match the second div

Source: MDN