Exchanging Words explainer

The aim of this puzzle: Change the text of an HTML element using JavaScript.

Walkthrough of the solution: The HTML contains 2 h1 elements inside the body. They each have their own id: post and description. These id values can be used in the JavaScript to access the specific elements.

The JS starter code uses document.getElementById('post') to get the h1 element with the post id. Then, .textContent is attached to access the text inside that element. The assignment operator, =, is then used to assign some new text, 'My First Project'.

Similar JS code can be used to change the text of the description element. Start by using document.getElementById('description') to access the description element. Then attach .textContent to that. Now, you can assign a new string to the element’s text content. For example: 'I made a webpage'.

Sample code solution:
(Tap below to reveal)
JS

document.getElementById('post').textContent = 'My First Project';
document.getElementById('description').textContent = 'I made a webpage';
HTML
<html>
  <body>
    <h1 id='post'>Title</h1>
    <h1 id='description'>Description goes here</h1>
  </body>
</html>
CSS
body {
  background-color: navy;
}

h1 {
  color: white;
}

#description {
  color: gray;
}

JavaScript Concepts: document.getElementById(), .textContent, Assignment Expression =
HTML Concepts: HTML element, <html>, <body>, id, <h1>

1 Like

This is not too obvious, though I have probably understood it. These are not functions previously learned in JS.
document takes a document, could be a txt file on the PC;
.getElementById(…) is a method inside JS which finds an element with xxx name;
.textContent takes a property previously assigned to an object name, i.e. xxx.

I wonder why getElementById uses capital letters. I assume this is a function which was previously created, and is not an integrated JS method.

Correct me if I am wrong.
##update getElementById does seem to be a basic expression in JS, even though it uses capital letters not previously seen in code. update##

2 Likes

Hey there, document is provided by the web browser’s API, and not part of the core JavaScript language. It represents the HTML document. This object provides a bunch of useful functions, like .getElementById() or createElement().

Here’s a good video explaining what APIs are.

You can read more about the browser’s APIs on MDN.

Hope this explains things. Let me know if you have questions.
Ben

2 Likes