1

Is there a way to find out whether a HTML-tagName comes in pair or alone (Standalone-Tag)? E.g. <div></div>, <em></em>, <p></p>, ... they come in pair, but <br/>, <input>, <area> ... are Standalone.

I need a function which should find out if a HTML-Code snippet is entered correct. Therefore the function has to investigate among others which HTML-Element can be created with Standalone-Tag. Do you have any idea how can I find out if an HTML element is standalone? Except for example something like this:

var myArray = [ list of Standalone-Tags ];
if(jQuery.inArray("test", myArray) != -1 ) { ... }

Thanks.

user3815508
  • 369
  • 4
  • 20
  • `$("
    ").html("
    ").html()` vs `$("
    ").html("
    ").html()`; but ideally you should grab the specs from W3.org.
    – Salman A Oct 13 '14 at 14:23
  • How are you defining "correctly"? [Any string is HTML](http://stackoverflow.com/a/15458987/497418), so if you want to sanitize it, just dump it into a document fragment and let the browser do the heavy lifting. – zzzzBov Oct 13 '14 at 14:27
  • @zzzzBov: Thanks, but the link was checked for syntax, not to "Stand Alone Tag". – user3815508 Oct 13 '14 at 14:40

1 Answers1

3

Browsers don't have a built in list of elements which are defined as empty.

You're most reliable bet would be to create one manually by reading the HTML specification.

Alternatively, you could create an element and see what the browser returns when you convert it to HTML.

var element = prompt("What element name? e.g. br");
var container = document.createElement('div');
var content = document.createElement(element);
container.appendChild(content);
var reg = new RegExp("/" + element);
alert(reg.test(container.innerHTML) ? "Not Empty" : "Empty");
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • But this is really an elegant and clever solution :) Just something I wanted, thank you. – user3815508 Oct 13 '14 at 14:54
  • The alternative way is more reliable as regards to what browsers really treat as “standalone” tags, since they may well support nonstandard void elements (and may fail to support standard void elements, for some values of “standard”). – Jukka K. Korpela Oct 13 '14 at 17:02