JavaScript DOM innerHTML Property

Learn via video course
FREE
View all courses
JavaScript Course With Certification: Unlocking the Power of JavaScript
JavaScript Course With Certification: Unlocking the Power of JavaScript
by Mrinal Bhattacharya
1000
4.8
Start Learning
JavaScript Course With Certification: Unlocking the Power of JavaScript
JavaScript Course With Certification: Unlocking the Power of JavaScript
by Mrinal Bhattacharya
1000
4.8
Start Learning
Topics Covered

Overview

This article provides an overview of how to use the innerHTML in JavaScript to manipulate the content of HTML elements in the Document Object Model (DOM). It also highlights the exceptions and security risks associated with innerHTML in Javascript. By understanding innerHTML in js, developers can enhance the interactivity and dynamic nature of their web pages.

What is JavaScript innerHTML?

When you look at your keyboard, you see that there are different keys and their corresponding labels on them. Say a key needs to be changed, what would you do? Would you buy a new keyboard or just modify that one key with a tool? Similarly, imagine the keyboard to be a webpage and all the keys in it as the HTML elements which make up the webpage, if you were to modify any HTML element the tool you use is innerHTML. What is JavaScript innerHTML

Definition:

innerHTML is a property associated with an HTML element, it is used to add HTML content into an HTML element as well as to get the HTML content present in an element Note : innerHTML applies to both HTML and XML content despite having only HTML in its name.

Takeaway:

innerHTML is used to modify the HTML content inside an element.

What is JavaScript innerText?

In the keyboard example given above let us say the label on the keyboard has faded would you remove the whole key or would just pasting a new label be enough? Similarly to modify the text inside an HTML element we use innerText. JavaScript innerText

Definition : innerText is a property associated with an HTML element, it is used to add text content into an element as well as to get the text content present in an element.

Takeaway: innerText is used to modify the text content inside an element.

Syntax

1. Setting HTML content inside an element:

innerHTML can be used to set content inside an element as follows:

Here newHTML is a HTML string which consists of elements and their content,by using innerHTML we have now set it inside sample_Element

Example:

HTML:

JS:

Output:

Explanation:

Here we have added the <p> element and its content inside the div with class as container by using innerHTML and the same is displayed on the webpage.

2. Getting the HTML content inside an element:

innerHTML returns the content inside an element as follows:

Using innerHTML on sample_Element i.e sample_Element.innerHTML will give us the html content present in sample_element and it is stored in the variable htmlContent.

Example:

HTML:

JS:

Console Output:

Explanation:

The div with the class as container has the <p> element inside it and the same was returned when we used innerHTML and consoled the value inside elemContent.

Takeaway:

Element.innerHTML is the syntax to use innerHTML. It can be used to get or set the content depending on which side of the equality operator it is used.

Value

  • One important thing to note is how the value/content of an element changes when we use innerHTML.
  • What happens is all of the HTML present in the element is removed and it is replaced with the ones we set using innerHTML.
  • You can imagine it like writing on a board we erase everything written and start anew.
  • The only way to avoid this is appending the HTML string we want to the HTML content already present in the element by using the + operator

Example:

Instead of,

we could do,

Example:

In the above example under 'Setting HTML content inside an element' we added <p> element inside the div, now let us try to add more HTML content into it by using innerHTML as sample_Element.innerHTML = newHTML syntax.

HTML:

JS:

Output:

Explanation:

As you can see the existing HTML content inside the div was replaced, now let us try using innerHTML and + operator as sample_Element.innerHTML += newHTML.

JS:

Output:

Explaination:

This works because the new HTML string has been concatenated with the one present inside container div.

Takeaway:

When using innerHTML the contents inside the element get replaced with the new content unless we use + to append.

Exceptions

There are two types of exceptions which can occur when using innerHTML depending upon what type of mistake was made while writing the code.

1. SyntaxError:

This exception is thrown when the html string used to set the value of innerHTML is not well formed.

Example:

HTML:

JS:

Console Output:

Explanation:

innerHTML gives error here because we have used a not well-formed string, we used double quotes again for computers ("computers") the compiler thinks the opening double quote for this word (the one at letter c) is the closing one for the whole line ( the one starting at <p>) and when it encounters the double quote again at the end of this word (after letter s) this is considered as an opening double quote and the one at the end of the line (after </p>) is considered as its closing double quote that means the word 'computers' is not part of the string and is considered unidentified by the compiler. Hence it throws the error SyntaxError: Unexpected identifier

2. NoModificationAllowedError:

This exception is throw when the parent of an element is the document element and we try to change the element's content using innerHTML.

Takeaway:

Two types of exceptions can arise when using innerHTML- SyntaxError and NoModificationAllowedError

Usage of innerHTML

a. Reading the HTML contents of an element using innerHTML:

innerHTML can be used to read the HTML of an element,the syntax for it is as follows:

Here innerHTML returns the all the nodes present in sample_Element and they are stored inside the variable contents.

Example:

HTML:

JS:

Console Output:

Explanation:

The div with class as container has the <h3> and <p> elements inside it and the same was returned when we used innerHTML and consoled the value inside elemContent.

Usage of innerhtml

Takeaway:

innerHTML can be used to read HTML contents of an element.

b. Replacing the contents of an element using innerHTML:

The contents of an element can be replaced if we set the value of an element's content using innerHTML,the syntax for it is as follows:

Here all the HTML(XML as well if it is present) inside sample_Element is replaced by what is present in newHTML string.

Example:

HTML:

JS:

Output:

Explanation:

As you can see the previous HTML content inside the div was replaced,this is because innerHTML returns all the HTML content present inside it , this means container.innerHTML was like a variable holding a HTML string inside it and here we assigned new value to it by using = hence the previous content was replaced. Replacing the contents of an element using innerHTML

Takeaway:

innerHTML can be used to replace HTML contents of an element.

c. Appending HTML to an element using innerHTML:

If we want don't want an element's content to be replaced we can just append our HTML to the element's content by using the + operator the syntax for it is as follows:

Here whatever content is there inside sample_Element will not be replaced, newHTML will be appended to it

Takeaway:

innerHTML can be used to append HTML contents of an element.

Example:

HTML:

JS:

Output:

Appending  HTML to an element using innerHTML

Explanation:

As explained in previous example, the containerElem.innerHTML is like a variable which contains a HTML string of all the HTML content present inside div container , here we used '+' operator which is act as a string concatination operator.Hence instead of replacing the existing HTML content the new content is being appended to it.

d. Operational details:

Let us look at what happens behind the scenes when we try to set the contents of an element by using innerHTML

  1. The string given by us is parsed as HTML or XML (depending on document type) and a DocumentFragment object (it is a light weight version of document object) is created.
  2. This DocumentFragment object contains the set of DOM nodes for the elements specified by us in the string.
  3. Then the contents of the element which we are trying to modify are replaced by the nodes in the new DocumentFragement

Takeaway:

A new DocumentFragement object is created based on the HTML string given by us. The nodes in this object replace the existing HTML content of the element.

e. Security Risks:

  • In websites where innerHTML is used to insert content into a page especially the ones which do this by using the input entered by the user, there is a chance for a cross-site scripting attack (XSS) which poses a security risk.
  • An XSS attack means that outsiders will be able to inject harmful code into the scripts which will be viewed and run by all the users who visit the site.
  • Let us look at the behaviour of innerHTML to understand more about how this could happen: Security Risks
  • Say the user entered the name as Scaler through the input field in the webpage, and it is rendered by using innerHTML ,this is a harmless scenario and everything works fine.
  • If the malicious user enters a html string then this will be displayed and cause changes in out webpage
  • Similarly malicious scripts could be injected as well.
  • To avoid such scenarios instead of innerHTML it is recommended to use : Element.setHTML : It does the same thing as innerHTML and in addition it sanitizes the string given. It removes any unsafe or otherwise unwanted elements, attributes, or comments. Node.textContent: When we are inserting plain text it is better to use textContent as it parses the inserted text as raw text instead of HTML.

Takeaway:

Using innerHTML is a security risk, use Element.setHTML and Node.textContent instead.

JavaScript innerText vs. innerHTML

JavaScript innerText vs. innerHTML

Although both are used to modify and return the contents of an element. There are some key differences between the two:

innerHTMLinnerText
innerHTML returns all the elements present in an element and also the content inside theminnerText returns only the text inside an element
innerHTML considers spacinginnerText does not consider spacing

Let us look at some code to understand it better:

HTML:

JS code to check innerHTML result:

Console Output:

JS code to check innerText result:

Console Output:

Webpage Output for both:

Quote by Peter Norwig:

We dont have better algorithms, we just have more data

Explanation :

  • We can see from the outputs that innerHTML returned the elements and the content inside them as well but innerText returned only the text.
  • innerHTML considered the gap in algorithms we and returned it as is, but innerText ignored it.
  • The reason for this is innerText returns only the rendered text of a node this means what would be displayed on the webpage only that is returned, here as seen in the output innerText does exactly that.
  • innerHTML returns all the nodes present inside the specified element irrespective of how it is being rendered hence we got both the elements and the gap as well in the output.

Takeaway:

innerHTML returns all the elements and their text as well along with the specified spacing, innerText returns only text with no consideration to spacing.

Examples

a. Example of innerHTML property with show/hide comment form

HTML:

JS:

Output: innerHTML property with show/hide comment form

Explanation:

  • This code shows the comment form with the click of the 'comment' button.
  • In the HTML file we have a div element with id cmnt-block we are adding and removing the comment form to this element by using innerHTML
  • In the JS file we have created a variable commentForm and its value is a string that has the HTML elements needed to create a form
  • Based on the flag which determines whether the form is hidden or displayed we insert this comment form into the div.
  • commentBlock.innerHTML = commentForm line adds the contents inside commentForm to cmnt-block div
  • commentBlock.innerHTML = "" line replaces whatever was added to cmnt-block div with an empty string

b. Creating mechanism for logging messages into a box on a web page using innerHTML:

HTML:

JS:

Output: logging messages into a box on a web page using innerHTML

Explanation:

  • This code logs the time on the web page when the Click Me! button is clicked by the user.
  • In the HTML file we have a div element with class log inside the box div we are adding logs to this element by using innerHTML.
  • In the JS file the key line is logElem.innerHTML += timeStr + ": " + msg + "<br/>" it means whenever the Click Me! button is clicked the string having the current time and a log message is appended to the content in log div.
  • Note that the reason the content is not being replaced like in the previous code is that here we are appending to the content already present inside the element by using the + operator.

Conclusion:

  • innerHTML is used to:
    1. Read the HTML contents of an element
    2. Replace the contents of an element
    3. Append HTML to an element
  • Syntax to use innerHTML is Element.innerHTML
  • innerText can only modify the text content of an element
  • innerHTML can give two types of exceptions: SyntaxError and NoModificationAllowedError
  • Using innerHTML is a security risk, use Element.setHTML and Node.textContent instead.

learn more about JavaScript Document Object Model with Scaler Topics.