Wednesday, February 18, 2015

JavaScript: outerHTML

This JavaScript method will work on Internet Explorer 8 and above, and of course on latest Chrome, Firefox, Opera, etc.

Just like innerHTML method, this one can also do the get or set process for an HTML DOM element.


The Difference
With the innerHTML method, we can get or set the content of a particular parent element, the inner part.
With the outerHTML method, we will get or set the parent element reference itself.

Syntax
It's the same as innerHTML method.


Get
var parent_element = someElement.outerHTML;
The variable parent_element will have all the content plus the parent element of that someElement variable.


Set
someElement.outerHTML = "<div id='replacement'>New content</div>";
The variable someElement (which is the representation of a particular DOM element) will all be replaced with the new content plus the wrapper (parent element) declared above.

That's about it. You can try it out on CodePen or other places or just on your browser (via console on Chrome/Opera or script editor on Firefox).

No comments:

Post a Comment

Tell me what you think...