Menu
Coddy logo textTech

getElementById

Lesson 3 of 13 in Coddy's JavaScript DOM Methods course.

The function getElementById() retrieves the first element with a matching id attribute, for example:

const element = document.getElementById("elementId");																					

The above retrieves the element with an id of elementId and saves it to a variable called element.

Note the document prefix, this is the HTML file DOM.

After you retrieve an element, you can manipulate it using JavaScript!

The first property we will learn is textContent which holds the element text content. You can modify the text like this:

const element = document.getElementById("elementId");
element.textContent = "some text";

After this code, the text of #elementId will be some text 

challenge icon

Challenge

Easy

You are given HTML code that contains heading with an ID.

Using JavaScript only, change the text of this element to “Hello!”:

  1. Retrieve the element using getElementById function.
  2. Modify the text of the element using textContent property.

Try it yourself

<!DOCTYPE html>
<html>
    <body>
        <h1 id="heading">Welcome!</h1>
        <script src="script.js"></script>
    </body>
</html>

All lessons in JavaScript DOM Methods