innerText and innerHTML - Java Script

Despite the advantages that the DOM brought to dynamically modifying documents,it wasn’t enough for the developers at Microsoft.Internet Explorer 4.0 introduced two properties on all elements designed to ease the manipulation of the document called innerText and innerHTML.

The innerText property is designed to modify text between a starting and ending tag.For example,suppose you have an empty <div/> element that you wanted to change to <div>New text for the div.</div>.Using the DOM,you do this:

oDiv.appendChild(document.createTextNode(“New text for the div.”));

This code isn’t difficult, but it is a bit verbose.Using innerText,you can just do this:

oDiv.innerText = “New text for the div.”;

Using innerText,the code is much simpler and easier to understand.Additionally, innerText automatically HTML-encodes any less-than,greater-than,quote, and ampersand characters so you never have to worry about them:

oDiv.innerText = “New text for the <div/>.”;

This line of code results in <div>New text for the &lt;div/&gt;.</div>.But what if you want to include HTML tags inside of the element as well? That’s where innerHTML comes in.The innerHTML property enables you to assign HTML strings to an element without worrying about creating elements using the DOM methods.For example,suppose an empty <div/> needs to become <div><strong>Hello</strong> <em>World</em></div>.Using the DOM,this is the code you use:

Seven lines of code down to one line of code, that’s the power of innerHTML!
You can also use innerText and innerHTML to get the contents of an element.If an element has only text, innerText and innerHTML return the exact same value. If,however,it has elements and text,innerText returns only the text portions, and innerHTML returns the HTML code for all elements and text.The following table lists the different values for innerText and innerHTML based on certain code.

innerText and innerHTML

Ultimately,this means that you can strip out all HTML tags from a given element by setting innerText to equal itself:

oDiv.innerText = oDiv.innerText;

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

Java Script Topics