Select Page Element By ID
Select An Element By ID
Let's take a look at how we can use JavaScript and the DOM to gain access to specific elements using their ID attribute.
Remember thedocument
object from the previous section? Well, we're going to start using it! Remember thedocument
object is an object, just like a JavaScript object. This means it has key/value pairs. Some of the values are just pieces of data, while others are functions (also known as methods!) that provide some type of functionality. The first DOM method that we'll be looking at is the.getElementById()
method:
document.getElementById();
If we ran the code above in the console, we wouldn't get anything, because we did not tell it the ID of any element to get! We need to pass a string to.getElementById()
of the ID of the element that we want it to find and subsequently return to us:
document.getElementById('footer');
One thing to notice right off the bat, is that we're passing'footer'
, not'#footer'
. It already knows that it's searching for an ID (its nameis"getElementById", for a reason!).
If you'd like to read more about this method, check out its documentation page on MDN:https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById
Let's use this MDN documentation page to try out using this method.
To recap what we just did:
- we opened the DevTools for the page we were looking at
- we switched to the Console pane
- we ran `document.getElementById('content'); on the console
Running this code cause thedocument
object to search through its entire tree-like structure for the element that has an ID of "content".
Now it's your turn!
Task List
I loaded the HTML page
I opened the DevTools
I switched to the Console pane
I used
document.getElementById()
to locate an element by its ID
QUESTION 1 OF 3
Now, what do you think will happen if you useddocument.getElementById(<some-nonexistent-ID>)
to search for some ID that doesn't actually exist in the HTML page?
a dummy element will be returned
false
will be returnednull
will be returnedit will cause an error
SUBMIT
QUESTION 2 OF 3
Which of the following will select the element with the ID oflogo
?
document.getElementById('logo');
document.getElementByID('logo');
document.getElementById('#logo');
SUBMIT
Write the DOM code to select the element with IDstrawberry-banner
.
SUBMIT
Selecting By ID Recap
In this section, we learned how to select a DOM element by its ID:
.getElementById()
There are a couple of important things to keep in mind about this method:
- it is called on the
document
object - it returns a _single _item
// select the element with the ID "callout"
document.getElementById('callout');
Further Research
- .getElementById() on MDN