Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery detect if a tag is self closing

Tags:

jquery

Is there a way to detect if a tag is self closing with JQuery like an image tag? Something dynamic not just an image tag.

if ($('.selector')[0].tagName.toLowerCase()=="img") {
    // do something
}
like image 801
Hatchware Avatar asked Feb 18 '10 21:02

Hatchware


2 Answers

You need a little background. The HTML markup that's sent across the wire is parsed by the browser into a DOM tree. At the point, the original markup is gone, served it's purpose, and no longer exists. When you do innerHTML on an element, that's not the literal HTML that generated the element, but the browser's serialization of that DOM subtree.

The point is, there is no different between <div /> and <div></div>. So just see if it has any children. If it doesn't, the element does have a possible XHTML representation that uses a self-closing tag.

element.children().length == 0

or as cletus says:

element.is(":empty")
like image 103
jpsimons Avatar answered Nov 09 '22 11:11

jpsimons


jQuery uses this list internally:

/^(?:area|br|col|embed|hr|img|input|link|meta|param)$/i

You can do the same:

if(/^(?:area|br|col|embed|hr|img|input|link|meta|param)$/i.test($('.selector')[0].tagName)) {
//do something
}
like image 13
Nick Craver Avatar answered Nov 09 '22 12:11

Nick Craver