InnerHTML vs InnerText

isiakaabd

ISIAKA ABDULAHI AKINKUNMI

Posted on December 16, 2022

InnerHTML vs InnerText

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;

Enter fullscreen mode Exit fullscreen mode

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;

Enter fullscreen mode Exit fullscreen mode

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.

💖 💪 🙅 🚩
isiakaabd
ISIAKA ABDULAHI AKINKUNMI

Posted on December 16, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related