Inject HTML using JS
Lesson 15 of 18 in Coddy's Moving Clouds - HTML/CSS/JS Project course.
In the next two lessons, we will inject the clouds using JavaScript!
The document.getElementById() method returns an element object representing the element whose id property matches the specified string. Since element IDs are required to be unique if specified, they're a useful way to get access to a specific element quickly. For example:
const elem = document.getElementById("myid");The following example, gets the element with id “myid” and stores it in a variable called elem.
After you get an element object, you can replace its inner HTML:
elem.innerHTML = '<p>Hello!</p>';For example, if your HTML code is:
<div id="myid">
</div>After the above injection, the HTML code will look like this:
<div id="myid">
<p>Hello!</p>
</div>Challenge
EasyYour task is to inject the h1 tag with the text "Some text" into the element whose id equals “container” (our cloud container).
Add the new code to the start of your JavaScript file, don't delete anything you have already done.
Note: It should override the existing cloud element, don't worry, we will get the cloud back in the next lesson.
Try it yourself
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<!-- Write HTML code here -->
<script src="script.js"></script>
</body>
</html>