Log in from a computer to take this course

You'll need to log in from a computer to start Building Interactive JavaScript Websites. But you can practice or keep up your coding streak with the Codecademy Go app. Download the app to get started.

apple storegoogle store
Learn

In the previous exercise, we accessed the <body> element with the document keyword!

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.

CSS selectors define the elements to which a set of CSS rules apply, but we can also use these same selectors to access DOM elements with JavaScript! Selectors can include a tag name, a class, or an ID.

The .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.

document.querySelector('p');

Along with .querySelector(), JavaScript has more targeted methods that select elements based on their class, id, or tag name.

For example, if you want to access an element directly by its id, you can use the aptly named .getElementById() method:

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 .getElementsByClassName() and .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')[0].innerHTML = 'Not yet registered'; // Set second <li> tag as 'Cedric Diggory' document.getElementsByTagName('li')[1].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.

Instructions

1.

Use the .querySelector() method to select the first 'h1' element. Access that element’s .innerHTML property to change the h1 title to 'Most popular Harry Potter characters'.

2.

Use the .getElementById() method to access the element with an ID of 'fourth'. Set that element’s inner HTML to read 'Professor Snape'.

3.

Use the .getElementsByClassName() method to access the first element with the class name of 'slytherin'. Replace that element’s inner HTML with the text 'Salazar Slytherin'.

4.

Use the .getElementsByTagName() method to access the first element with the <li> tag. Access that element’s .innerHTML to replace the content to read 'Dobby'.

Sign up to start coding

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?