Alex Rivera | Logout

JQuery detect if a tag is self closing

Asked 2010-02-18T21:41:59.703
10

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
}
Edit
Report

2 Answers

4

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")
answered 2010-02-18T22:00:02.810
3

Do you need to distinguish between an element that's empty vs self-closing? If not, you can use:

if ($(".selector").is(":empty")) {
  // do something
}

But if you're talking about detecting whether a given HTML tag should be empty or not, no you can't do that programmatically because you're not stopped from creating invalid HTML and you need to validate it against a DTD to find out.

answered 2010-02-18T21:45:16.220

Your Answer