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
documentprefix, 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
EasyYou are given HTML code that contains heading with an ID.
Using JavaScript only, change the text of this element to “Hello!”:
- Retrieve the element using
getElementByIdfunction. - Modify the text of the element using
textContentproperty.
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
2DOM Methods I
getElementByIdModify Element StylegetElementsByClassNameLoop Through and ManipulategetElementsByTagNamequerySelector