Codepath

Modifying Attributes of HTML Elements

Introducing the innerHTML property!

The DOM is used to create references to HTML element. In this section we will look at how the DOM can be used to get or change the contents of an element.

The innerHTML property can be used to get the contents of an Element. Remember that for HTML elements, its contents are what is contained between the opening and closing tags.

Unlike DOM methods (like querySelector), in order to use a property in JavaScript, we use the symbol . after an element, or variable containing an Element type.

elementName.innerHTML = htmlString;
  • elementName.innerHTML: This will return the contents of elementName.
  • =: Symbol used to assign a value.
  • htmlString: The new value we want to assign the contents of elementName.
  • ;: Don't forget that all JavaScript statements must end in a semicolon;.

Inserting Elements using innerHTML

In the last section we saw how innerHTML property can be used to change the contents of an element by changing the text displayed for student information. However, this property can do so much more! In fact, developers can use the innerHTML property to inject or insert HTML elements into the webpage. Let's think about why we might additional HTML elements on the script as opposed to on the HTML document itself!

The HTML document holds the structure, or skeleton, of the website itself. We can manipulate the structure slightly from the script but overall, the structure of the website remains the same from when we initialize it with our index.html page. Let's think about examples of when we might modify what is visible to the page from the script.

  1. Adding a pop up when a user clicks on a button.
  2. Implementing an "infinite scroll" or adding more results as a user reaches the bottom of our page.
  3. Changing the contents on a page based on user input.
  4. Add status updates for events (uploading, downloading, etc.)

Adding HTML elements on the script side can give users the appearance of a "new" page without reloading the entire page. This can be less demand on the server side with dynamic changes. Let's take a look at the syntax for injecting HTML elements with the use of the innerHTML property.

divElement.innerHTML += `
  <!-- Insert HTML elements here -->
  <p>New HTML elements!</p>
`
  • divElement: When injecting HTML elements, this is typically added to div elements in the HTML document. This way it is easy to contain or group the new elements together without disrupting the existing layout.
  • +=: This operator allows us to append or add values to an existing variable. Unlike the = operator which replaces and reassigns a value to a variable, the += add and updates the value of the existing variable.
  • ``: Inside of the `` symbol we can add the HTML elements we wish to add. New injected elements will be added below any existing elements.
Fork me on GitHub