Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
DOM Manipulation
3.
What is JavaScript innerHTML?
3.1.
Syntax
3.2.
Explanation
3.3.
Code Implementation
3.3.1.
HTML Code
3.3.2.
Script
3.3.3.
Output
3.3.4.
Explanation
4.
Getting The innerHTML Property Of An Element
4.1.
Code Implementation
4.1.1.
HTML code
4.1.2.
Script 
4.1.3.
Output
4.1.4.
Explanation
5.
Setting The innerHTML Property Of An Element
5.1.
Code Implementation
5.1.1.
HTML code
5.1.2.
Script
5.1.3.
Output
5.1.4.
Explanation
6.
Manipulating HTML with innerHTML in JavaScript
6.1.
Adding content
6.2.
Code Implementation
6.2.1.
HTML code
6.2.2.
Script
6.2.3.
Output
6.2.4.
Explanation
6.3.
Removing Content
6.3.1.
HTML code
6.3.2.
Script
6.3.3.
Output
7.
Use cases of innerHTML
8.
Exceptions with innerHTML
9.
Security Concern with using innerHTML
10.
Difference between innerHTML, textContent and innerText
11.
Frequently Asked Questions
11.1.
How to append innerHTML in JavaScript?
11.2.
What is the replacement of innerHTML in JavaScript?
11.3.
How to get table innerHTML in JavaScript?
11.4.
How to parse innerHTML in JavaScript?
11.5.
How can we sanitize user input data before inserting it using innerHTML?
11.6.
What is the main difference between innerHTML and insertAdjacentHTML?
11.7.
What will happen to any event listener or data to an element when its content is modified using innerHTML?
12.
Conclusion
Last Updated: Mar 27, 2024
Easy

Understanding the innerHTML Property in JavaScript DOM

Author Vidhi Sareen
0 upvote
Create a resume that lands you SDE interviews at MAANG
Speaker
Anubhav Sinha
SDE-2 @
12 Jun, 2024 @ 01:30 PM

Introduction

The innerHTML is a property that is linked with the HTML elements. It is mainly used to generate dynamic HTML content like registration forms, comment forms, links, etc. You can change the content of the page without refreshing the page. This creates a positive impact on the user. You can use the 'getElementById()’,’getElementByClassName()' method, or other methods within Javascript code to link it with the HTML element and change its contents.

JavaScript innerhtml

In this article, we will learn what Javascript inner HTML is and how it works. 

DOM Manipulation

DOM manipulation is the process of changing the style, structure, or content of a document using JavaScript. The document is represented by a DOM-like tree structure. Each node in this represents a document element. Each node has unique properties. The developer can perform different actions on this structure, like adding, deleting, updating, or moving from one place to another in this DOM manipulation. Dom manipulation can be used to create a variety of effects, like adding or deleting elements from the page, changing the content or style of the element, adding an event handler to an element, and many more.

The image below shows a visual representation of the DOM tree.

DOM manipulation
  • Document is the core of the DOM. It is used to represent the entire HTML document.
     
  • HTML elements are root elements of the DOM. It is the parent of all other elements in the document.
     
  • The Body and Head elements are the children of HTML elements. They are siblings to each other which indicates that they have the same parent.
     
  • The Title element is the child of the head element. It takes care of the text that needs to appear in the title bar.
     
  • Tag and h1 tag are children to the Body element. They are siblings to each other.
     
  • The "href" attribute is the child of the a(anchor) tag.
Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

What is JavaScript innerHTML?

In JavaScript, innerHTML refers to the content of the HTML element. It is used to set a property or add content to a specific HTML element. Let's consider an example where you have created a div tag in HTML, and inside this tag, we have generated another paragraph tag. So the inner HTML is the paragraph tag, and the other whole div is the outer HTML.

Syntax

document.getElementById(‘id of that particular element’).innerHTML=’content you want to add’

Explanation

In this case, 'id of that particular element' refers to the ID of the HTML element you want to use and 'content you want to add' refers to the fresh content you want to insert into that specific element. It returns a string containing the HTML content of that particular element. We can easily replace the existing content with the new element by changing the value of the innerHTML. 

Let's look at a small example to understand this syntax and concept more clearly.

Code Implementation

HTML Code

<!DOCTYPE html>
<html>
  <head>
    <title>Coding Ninja</title>
  </head>
  <body>
    <h1>My Course List</h1>    


 <!----list of course with ID of “course-list”--->
 <ul id="course-list">
      <li>Java</li>
      <li>C++</li>
      <li>Python</li>
    </ul>
 
    <!------Script tag to load JavaScript file—>
    <script src="script.js"></script>
  </body>
</html>

Script

// used innerHTML property to get the items of the list
var u = document.getElementById("course");
       
       //used to get the list
        console.log(u)


// used innerHTML property to get the items of the list
var u = document.getElementById("course");
       
       //used innerHTML to get the inner item of the list
        console.log(u.innerHTML)

Output

output
output

Explanation

In this example, the getElementById() function is used to get a list of elements with the id="course" attribute. The innerHTML method was then used to retrieve the list's inner content. When you assign the 'innerHTML' attribute to an element, you can easily replace the old content with the new one.

Getting The innerHTML Property Of An Element

Using innerHTML, JavaScript can access the inner element of the element object. The innerHTML property returns the HTML content of the element, not the element itself. Taking an example to understand it better.

Code Implementation

HTML code

<!DOCTYPE html>
<html>
<body style= "text-align: left">
<h1 style= "color:orangered">
Coding Ninjas
</h1>
<h2>
Course offered by Coding Ninjas
</h2>
<ul id="course">
        <li>Java</li>
            <ul id="Java">
                
                <!-----Created a sublist of Java course —>
                <li>Basic java course</li>
                <li>Advanced Java Course</li>
            </ul>
        <li>CSS</li>
        <li>C++</li>
            <ul id ="C++">
              
                <!-----Created a sublist of C++ course —>
                <li>Basic C++ Course</li>
                <li>Advanced C++ Course</li>
            </ul>
        <li>Python</li>
      </ul>      
    <script src="script.js"></script>
</body>
</html>

Script 

var u = document.getElementById("C++");
        console.log(u.innerHTML);

Output

output

Explanation

In this example, we are taking the inner elements of the C++ list. The innerHTML property can be used dynamically to change the web page content, like if you want to add or remove some features from the list.

Setting The innerHTML Property Of An Element

We can set the value of content using innerHTML.The inner HTML property can be used to set the HTML content but cannot add a new element to an object . If you want to add a new element to an object you can use the appendChild() method. Setting the innerHTML property of an element is helpful while making a webpage and constantly wanting to add or delete elements. Let's look at the example for a clear understanding of this.

Code Implementation

HTML code

<!DOCTYPE html>
<html>
<body style= "text-align: left">
    
    <!----added div element with id “mydiv”----->
    <div id="mydiv"></div>
<h1 style= "color:orangered">
Coding Ninjas
</h1>
<h2>
Course offered by Coding Ninjas
</h2>
<ul id="course">
        <li>Java</li>
            <ul id="Java">
                <li>Basic java course</li>
                <li>Advanced Java Course</li>
            </ul>
        <li>CSS</li>
        <li>C++</li>
            <ul id ="C++">
                <li>Basic C++ Course</li>
                <li>Advanced C++ Course</li>
            </ul>
        <li>Python</li>
      </ul>    
      <script src="script.js"></script>
      </body>
</html>

Script

//used the innerHTML method to add content to 
   Const mydiv = document.getElementById("mydiv");

//setting the new content
   mydiv.innerHTML = "<h1>Welcome to Coding Ninjas website!</h1>";

Output

output

Explanation

In this example, the JavaScript code selects the <div> element using document.get.ElementById() method. The innerHTML is used to replace the content of the div with new content in the form of a string in the <h1> tag.

Manipulating HTML with innerHTML in JavaScript

Adding content

To add the content in the HTML we have used ‘innerHTML’. Here is an example which explains how we can add content to an element.

Code Implementation

HTML code

!DOCTYPE html>
<html>

<body style="text-align: left">
    <div id="myDiv"></div>
<h1 style="color:orangered">
Coding Ninjas
</h1>
<h2>
Course offered by Coding Ninjas
</h2>

<!-----created list of course—--->
<ul id="course">
        <li>Java</li>
            <ul id="Java">
                <li>Basic java course</li>
                <li>Advanced Java Course</li>
            </ul>
        <li>CSS</li>
        <li>C++</li>
            <ul id ="C++">
                <li>Basic C++ Course</li>
                <li>Advanced C++ Course</li>
            </ul>
        <li>Python</li>
      </ul>    

	  <!------created a class named offer—->
      <div class =”offer">
        <p>Early Bird Offer</p>
      </div>
   <script src="script.js"></script>
 </body>


</html>

Script

//Get the element from the class named offer
 const offer_value = document.querySelector("offer")


//add the string to the element
 offer_value.innerHTML += "<p>Don't Miss Out This Wonderful Opportunity</p>";

Output

output

Explanation

We have created a class named as offer. In this we are adding a new content which says that “Don’t Miss Out This Wonderful Opportunity”.

Removing Content

To remove the content from an element using ‘innerHTML’ we have assigned a empty string to the property.

HTML code

!DOCTYPE html>
<html>

<body style="text-align: left">
    <div id="myDiv"></div>
<h1 style="color:orangered">
Coding Ninjas
</h1>
<h2>
Course offered by Coding Ninjas
</h2>

<!-----created list of course—--->
<ul id="course">
        <li>Java</li>
            <ul id="Java">
                <li>Basic java course</li>
                <li>Advanced Java Course</li>
            </ul>
        <li>CSS</li>
        <li>C++</li>
            <ul id ="C++">
                <li>Basic C++ Course</li>
                <li>Advanced C++ Course</li>
            </ul>
        <li>Python</li>
      </ul>    

       <!------created a class named offer—->
      <div class =”offer">
        <p>Early Bird Offer</p>
      </div>
   <script src="script.js"></script>
 </body>

</html>

Script

//get the element with the class “
const offer_value = document.querySelector("offer")
       
//removing content from the element
offer_value.innerHTML = ' ';

Output

Output

Use cases of innerHTML

There are many use cases of innerHTML, but here are some important use cases where innerHTML is mainly used.

  • Add new content to the web page in response to the user action.It can be through submitting a form or clicking a button.“innerHTML” is also used to update the web page's content in real time.
     
  • It is used dynamically in areas where you want to generate content based on external source data.
     
  • They are used to create new HTML elements like pop-up windows.
     
  • They are used in areas where you want to change the website's design and view it frequently.

Exceptions with innerHTML

When using innerHTML in JavaScript, be aware of exceptions:

  • Invalid HTML: Setting innerHTML with invalid HTML can throw a DOMException
     
  • XSS Vulnerabilities: Inserting user-generated content without sanitization can lead to security risks
     
  • Performance: Frequent updates with innerHTML for large DOM structures may slow down the page
     
  • Event Listeners: Replacing content with innerHTML may remove event listeners

Security Concern with using innerHTML

Security Concern with using innerHTML

While using innerHTML to modify the content of the object, especially in cases where the user enters the input, that may create some security concerns one must keep in mind before using it.

There are some chances for cross-site scripting attacks(XSS). This can allow the attacker to steal important information or perform unwanted actions on the user's behalf. To prevent XSS attack, it's important to sanitize any input given by the user or check if the input data is in the correct format before adding it to the HTML code. 

Alternative ways to prevent XSS attacks can be:

  • Element. insert.AdjacentHTML(): it allows you to insert HTML code at a specific location without overwriting it.
     
  • Element.textContent(): textContent is used to insert raw text instead of an HTML code that will help in preventing XSS attack
     
  • Another alternative is to use a third-party library that will provide a safer method for inserting a HTML code.

Difference between innerHTML, textContent and innerText

InnerHTML textContent innerText
Gets or sets the content inside the element. Gets or sets the text content inside the element. Same as that of textContent but preserves white spaces.
It returns HTML tags, modified element style and modified element content. It does not return HTML tags or Modified element content but it returns modified content. It does not return HTML tags or Modified element content but it returns modified content.
It is not recommended to use because of security risks. More secure as compared to innerHTML. More secure as compared to innerHTML because it can only return the visible text of an element.

Frequently Asked Questions

How to append innerHTML in JavaScript?

To append content to an HTML element using JavaScript, you can access the element using its ID or other selection methods and then modify its innerHTML property.

What is the replacement of innerHTML in JavaScript?

A safer alternative to innerHTML is the textContent property. It sets or returns the text content of an HTML element, ensuring that any content added is treated as plain text and not as HTML. This reduces the risk of security vulnerabilities like cross-site scripting (XSS) attacks.

How to get table innerHTML in JavaScript?

To get the innerHTML of a table element in JavaScript, you can select the table by its ID or other methods and then access its innerHTML property.

How to parse innerHTML in JavaScript?

If you want to parse the innerHTML content as HTML nodes or manipulate it, you can use the DOMParser API. This allows you to create a new HTML document and parse the innerHTML as a DOM tree. 

How can we sanitize user input data before inserting it using innerHTML?

You can sanitize input data in different ways, like using libraries and frameworks like DOMPurify or Sanitize.js. You can even use regular expressions to remove unwanted characters. The 'CreateTextNode' method can also be used to sanitize input data.

What is the main difference between innerHTML and insertAdjacentHTML?

The main difference between innerHTML and insertAdjacentHTML is that innerHTML replaces the entire content. In contrast, insertAdjacentHTML allows you to add new content at a specific location without disturbing the existing content.

What will happen to any event listener or data to an element when its content is modified using innerHTML?

The content of the data will be lost. ‘innerHTML’ replaces the entire content, even the event listener or data. You can use 'appendChild' or 'insertAdjacentHTML' to prevent this.

Conclusion

The innerHTML property in JavaScript is a powerful tool for dynamically adding or modifying the HTML content on a web page. The developer can add, delete, change, or replace HTML content using JavaScript without reloading the web page. Since innerHTML is a widely used method, it has some limitations regarding security risk. As discussed in the article above, it can be prevented by using alternative ways. Overall, innerHTML is used for creating interactive web pages in web development.

To learn more about this topic, check out the link below

You can find more informative articles or blogs on our platform. You can also practice more coding problems and prepare for interview questions from well-known companies on your platform, Coding Ninjas Studio.

Live masterclass