Greg’s Sandbox

Notes on Front-End Web Development

12 Jan modified: 3 years ago

innerHTML

javascript Jon Duckett | JavaScript and JQuery

a project inspired by Tony de Araujo

Ever wonder how you could change the contents of an HTML element? Maybe you'd like to replace the text in a paragraph to reflect what a visitor has just selected from a drop down box. By manipulating an element's innerHtml you'll be able to change your text and HTML as much as you like.

Each HTML element has an innerHTML property that defines both the HTML code and the text that occurs between that element's opening and closing tag. By changing an element's innerHTML after some user interaction, you can make much more interactive pages.

However, using innerHTML requires some preparation if you want to be able to use it easily and reliably. First, you must give the element you wish to change an id. With that id in place you will be able to use the getElementById function, which works on all browsers.

We can use innerHTML either to retrieve the current content of the container or to insert new content into that container. Let's look at some examples. Here's are a div container that we might have in our HTML.

<div class="part2">
<h3>Standard Method (DOM Level 2)</h3>
<p>What method is used to make an item "click-able"?
  <br><i id="reply1">Click for Answer!</i>
</p>
<p>Is there a JavaScript method equivalent to css :hover?
  <br><i id="reply2">Click for Answer!</i>
</p>
<p>What methods are used to reveal and alter HTML?
  <br><i class="reply3 color">Click for Answer!</i>
</p>
</div>

Security Warning: Improper handling of the innerHTML property can enable script-injection attacks. When accepting text from an untrusted source (such as the query string of a URL), use createTextNode to convert the HTML to text, and append the element to the document using appendChild.

Continue reading innerHTML ...