In the previous exercise, we accessed the
<body> element with the
What if we wanted to select a specific element besides the entire
<body> element? The DOM interface allows us to access a specific element with CSS selectors.
.querySelector() method allows us to specify a CSS selector as a string and returns the first element that matches that selector. The following code would return the first paragraph in the document.
For example, if you want to access an element directly by its
id, you can use the aptly named
document.getElementById('bio').innerHTML = 'The description';
In this example, we’ve selected the element with an ID of
'bio' and set its
.innerHTML to the text
'The description'. Notice that the ID is passed as a string, wrapped in quotation marks (
There are also the
.getElementsByTagName() methods which return an array of elements, instead of just one element. You can use bracket notation to access individual elements of an array:
// Set first element of .student class as 'Not yet registered' document.getElementsByClassName('student').innerHTML = 'Not yet registered'; // Set second <li> tag as 'Cedric Diggory' document.getElementsByTagName('li').innerHTML = 'Cedric Diggory`;
In the above example code, the first element with the
'student' class and the second
<li> element have had their inner HTML changed.
.querySelector() method to select the first
Access that element’s
.innerHTML property to change the
h1 title to
'Most popular Harry Potter characters'.
.getElementById() method to access the element with an ID of
'fourth'. Set that element’s inner HTML to read
.getElementsByClassName() method to access the first element with the class name of
'slytherin'. Replace that element’s inner HTML with the text
.getElementsByTagName() method to access the first element with the
<li> tag. Access that element’s
.innerHTML to replace the content to read