# Finding Elements
If you want to change content on the page, find out what the content inside an element is, move an element, or delete an element then you need to find it first.
let p = document.querySelector('p');
//find the first paragraph on the page
let ps = document.querySelectorAll('p');
//find ALL the paragraphs on the page
2
3
4
The querySelector
method will return an ElementNode
.
The querySelectorAll
method will return a NodeList
. A NodeList
can be thought of as an Array of ElementNodes.
When you want to make changes to a webpage or read the contents of a webpage with JavaScript then you need a way of locating elements. The three methods that you will use most frequently when accessing web page content are:
let element = document.querySelector(cssSelector); //returns a single element node
let nodes = document.querySelectorAll(cssSelector); //returns a NodeList
let element = document.getElementById(id); //returns a single element node
2
3
querySelector( )
and getElementById( )
search the webpage for the first element node that matches.
let anchor = document.querySelector('.main p a');
In the example above, the variable anchor will contain either null, if no match found, or the first anchor tag inside a paragraph inside an element with the className .main
. You can pass ANY valid CSS selector, as a string, to this method.
let foot = document.getElementById('footer');
In this example, the variable foot will contain either null or the element on the page that has the id footer
. You pass any string that should match an id of an element on your page.
querySelectorAll( )
will return a NodeList, which is similar to an Array in that it is a numbered list, but it can only contain HTML Nodes. When you call querySelectorAll( )
, it will ALWAYS return a NodeList. The NodeList might be empty, but it is still a NodeList with length zero.
let paragraphs = document.querySelectorAll('#main p');
The above example will return a NodeList containing ALL of the paragraphs inside the element with the id main
. Notice that this is a valid CSS selector, just like the querySelector( )
call above.