The querySelector() method
Coding with JavaScript
🕑 This lesson will take about 10 minutes
The document.querySelector() method is used to return the first element in a web page (document) that matches a CSS selector such as an element (like p, h1, img), a class or an id. This can be used in place of the document.getElementById() or document.getElementsByClassName() methods.
Here are some examples.
Get the first occurrence of a specific element
In this example, we will get the first occurrence of the <p> element using document.querySelector(). The type of element we want to get is placed between the parentheses and quotation marks eg. “p”, or “h1”, or “img”.
Get the first occurrence of an element belonging to a specific class
In this example, we will get the first occurrence of an element that belongs to a particular class using document.querySelector(). The class name of the element we want to get is placed between the parentheses and quotation marks (with a period before the class name) eg. “.myClass”.
Get the first occurrence of an element with a specific id
In this example, we will get the first occurrence of an element that has a particular id using document.querySelector(). The id of the element we want to get is placed between the parentheses and quotation marks (with a # before the id) eg. “#myID”.
Get the first occurrence of a specific type of element that belongs to a specific class
In this example, we will get the first occurrence of a specific type of element that belongs to a specific class using document.querySelector(). The type of element (eg. p, h1, img) is placed before the class name between the parentheses and quotation marks (with a period before the class) eg. “p.myClass” will get the first occurrence of an <p> element that belongs to the class called “myClass”.
Get the value from a text input element that has a specific id
In this example, we will use an event listener that will get the value from a text input element that has a specific id (“#myTextInput) when a button is clicked. The querySelector() method is used to attach the event listener to the button with the id “myButton”, get the value from the text input with the id “myTextInput”, and change the innerHTML content of the paragraph element with the id “message”.
The querySelectorAll() method
The querySelectorAll() method can be used to return all elements that match a CSS selector, not just the first element.
Next lesson: Working with text input