When trying to set the property of elements in Javascript, there are several similar ways of doing it, in this article I will explain what innerHTML
and innerText
are all about and their differences. Let's get started!!!
What's InnerHTML ?
innerHTML
is the property of an element that set or get the HTML
markup contained within an element. It contains HTML
tags like <li>
,<span>
, spacing and formatting. Let's create a p
element with some content as shown below
HTML
<p id="p"> This is an example of <strong>innerHTMl
</strong>text </p>
Javascript
let element = document.getElementById("p").innerHTML;
if we log
the value to console
we have
"This is an example of <strong>innerHTMl </strong> text"
Everything in between the p
element is shown without formatting and spacing.
Setting the value of an element's innerHTML
removes all of its descendants and replaces them with elements
constructed by parsing the HTML
given in the string.
element = "This has been changed"
Note: Whenever you add, append, delete or modify contents on a webpage using innerHTML
, all contents are replaced, also all the DOM nodes inside that element are reparsed and recreated, thereby making the process slow.
The use of innerHTML
also creates a potential security risk for your website. Malicious users can use cross-site scripting (XSS)
to add malicious client-side scripts that steal private user information stored in session cookies.
innerText
The innerText
property returns the rendered text content of an element that is visible in the browser. It doesn't return the content of <script>
and <style>
elements, It also neglects the spacing unlike innerHTML
. innerText
cannot access elements If elements are hidden by CSS properties like visibility and display.
HTML
<p id="p"> This is an example of <strong>innerText
</strong>text </p>
Javascript
let element = document.getElementById("p").innerText;
in the console, we have This is an example of innerText text
in the log.
When you set the innerText
property, all child nodes
are removed and replaced by only one new text node. innerText
is what you get when a user copies and pastes the content of an element. innerText
is best used when you need to retrieve the content of an element in plain text.
Thanks for Reading.
Top comments (4)
Your innerText JS snippet has an example about innerHTML, it should be about innerText; can you fix it?
Thanks for your observation. Its fixed now
Great article! Didn't know that
visibility: hidden
can not be accessed byinnerText
. Is it the same scenario withinnerHTML
?It shows the element's content in HTML markup, so the way you have written your code is shown regardless of the CSS. Visibility or display properties don't affect it