innerText and innerHTML: Understand the Difference
When working with HTML and JavaScript, you may come across two similar properties: innerText and innerHTML. While they may seem interchangeable at first glance, understanding their differences is crucial. In this article, we will delve into the disparities between innerText and innerHTML, exploring their definitions and providing examples to highlight their contrasting behaviors.
Difference: innerText and innerHTML
innerText | innerHTML | |
---|---|---|
Content | Returns visible text | Returns complete HTML content |
excluding HTML elements | including HTML elements | |
Format | Plain text | HTML structure as a string |
Usage | Retrieve or manipulate | Retrieve or manipulate |
text content | HTML structure | |
Example | <div>Hello, <b>world</b></div> | <div>Hello, <b>world</b></div> |
innerText returns: | innerHTML returns: | |
Hello, world | Hello, <b>world</b> |
innerText
innerText: The innerText property represents the visible text content within an element, excluding any HTML tags or elements nested within it. It provides access to the text content as a string, allowing developers to manipulate or retrieve it.
Example: Consider the following HTML snippet:
<div id="myDiv">
This is <b>bold</b> text.
</div>
JavaScript code:
const divElement = document.getElementById("myDiv");
console.log(divElement.innerText);
Output:
This is bold text.
Explanation: In this example, innerText returns the combined textual content of the myDiv
element, omitting the <b>
tags. It represents the visible text as it would be rendered on the web page.
innerHTML
innerHTML: The innerHTML property provides access to the HTML content within an element, including any nested tags or elements. It allows developers to modify or retrieve the entire HTML structure of an element as a string.
Example: Consider the same HTML snippet as before:
<div id="myDiv">
This is <b>bold</b> text.
</div>
JavaScript code:
const divElement = document.getElementById("myDiv");
console.log(divElement.innerHTML);
Output:
This is <b>bold</b> text.
Explanation
In this example, innerHTML returns the complete HTML content of the myDiv element, including the nested ‘<b>‘ tags. It represents the HTML structure as a string, providing access to modify or retrieve the entire content, including tags and elements.
Conclusion: Understanding the distinction between innerText and innerHTML is essential when working with HTML and JavaScript. While innerText focuses on the visible text content, excluding HTML elements, innerHTML provides access to the complete HTML structure, including nested tags. By utilizing these properties correctly, developers can manipulate or retrieve the desired content accurately, ensuring the proper functioning of their web applications.