outerText and outerHTML - Java Script

Along with innerText and innerHTML,Internet Explorer 4.0 also introduced outerText and outerHTML,which do exactly the same thing as their inner counterparts except that they replace the node in question. For example, setting outerText on a <div/> removes it and replaces it with a text node.

Consider the following line of code:

oDiv.outerText = “Hello world!”;

This single line of code is the same as this set of DOM manipulations:

The outerText property has the same rules as the innerText property in that it replaces all less-than, greater-than, quote, and ampersand characters with their HTML entities.Similarly, outerHTML behaves the same as innerHTML,creating all the necessary DOM nodes represented by the HTML string:

oDiv.outerHTML = “<p>This is a paragraph.</p>”;

This line of code performs the following DOM modifications:

Whereas outerText and outerHTML provide developers with a lot of power,they don’t clearly indicate exactly what is happening (the code doesn’t read).Many developers shy away from using outerText and outerHTML because they can lead to bigger headaches down the road if something goes wrong.

Generally speaking,you’re safer using the DOM methods,whose meanings are much clearer. Both these properties can also be used to get the contents of an element.The outerText property always returns the same value as innerText,regardless of the element contents.On the other hand, outerHTML returns the full HTML code for the element,including the element itself.The following table lists the different values for outerText and outerHTML based on certain code.

outerText and outerHTML based on certain code

Similar to innerText,you can use outerText in a unique way.By setting outerText equal to itself, you actually remove the element and replace it with a text node containing all the text inside the element:

When you click the button in this example,the <div/> is replaced with a text node containing This is my original text.You can tell that the <div/> no longer exists by using document.getElementById() to look for div1 again.In this example,the result of the function (null)is displayed in an alert.


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

Java Script Topics