Answer & Demo
You can detect if an element is self-enclosed via the following function, here is a JSFiddle with the demo.
HTML
<div>False</div><br>
<input type="text" value="True"/><br>
Two simple HTMLElement's
, the first one is not self enclosed, the second one is.
JavaScript
function isSelfEnclosed(element) {
var elem = document.createElement( element.tagName );
return elem.outerHTML.indexOf( "><" ) == -1;
}
isSelfEnclosed( div )
-> False, assuming div is the div element.
isSelfEnclosed( input )
-> True, assuming input is the input element.
Explanation
We make a new element after the element
's tag name, and we check if it's .outerHTML
has "><" in it.
Note
I made this self-answered question because the only other answer I found wasn't exactly bulletproof. Anyway it's a simple function with a simple purpose, hope it helps somebody!
Updates
- Updated incorrect code using
cloneNode( true )
instead of just cloneNode()
(17:01p.m 05/01/15)
- Updated function to more efficiently handle the problem (17:09p.m 05/01/15)