When the browser reads your HTML code, it creates something called the DOM (Document Object Model). The DOM is basically an interface that can be used to access or modify any of the HTML tags (elements) on your page.
var myButton = document.querySelector('#myButton');
The code shown above retrieves the element with id="myButton" from the DOM and stores it in a new variable called myButton. myButton can now be used to access or manipulate the button.
Notice that we tell querySelector which element we want by passing it a CSS selector. These are the same selectors you use to select elements you want to style in a CSS file.
If the selector passed to querySelector would select more than 1 element, only the first element is returned.
Works exactly the same as querySelector -- except it returns all the elements that match the CSS selector (not just the first).
querySelector and querySelectorAll are fully supported in all modern browsers (including IE9 [Internet Explorer 9] and above). This means 99.8% of the browser market is supported at this time. Only IE8 and below are not fully supported.
Using querySelector to find elements inside another element
<form id="loginForm"> <input type="text" name="userName"> </form> <script> var loginForm = document.querySelector('#loginForm'); // Search inside loginForm only var userName = loginForm.querySelector('input[name=userName]'); </script>
Notice that we used
loginForm.querySelector instead of
document.querySelector to get the userName.
What's the difference? Well, instead of searching the entire document,
we're only searching inside #loginForm.
This technique wasn't necessary in this situation, since the form had a unique id, but you'll sometimes need to do this when doing more complicated things. It also should offer better performance (if you already have the container saved to a variable), since it won't have to search the whole page.
Other (older) methods for getting elements from the DOM
Since, querySelector can do all of these things and more, you don't technically need these anymore. However, if you're just doing something simple (like retrieving an element by id or class), the older methods may be slightly faster than querySelector (since there isn't a CSS selector to parse).