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
}
Hatchware
  • 242
  • 2
  • 13

4 Answers4

14

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
}
Nick Craver
  • 623,446
  • 136
  • 1,297
  • 1,155
  • Solid answer, but tag is missing from this list. (Perhaps it was added within the last 8 years though :P) – Josh Powlison Nov 23 '18 at 01:40
  • Also realized: missing . Which is a much bigger deal. If you have inline SVGs that this code could touch, you'll also have tags among others. Edge case, but worth mentioning. – Josh Powlison Nov 23 '18 at 01:48
  • - For a list of self closing tag: [HTML5 spec] https://html.spec.whatwg.org/multipage/syntax.html#void-elements ; - Also, custom tags cannot be self closing tags > https://stackoverflow.com/questions/23961178/do-custom-elements-require-a-close-tag – Nor.Z Feb 13 '23 at 05:07
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")
jpsimons
  • 27,382
  • 3
  • 35
  • 45
  • 1
    `children()` does not return text nodes. As jQuery implements it, you should use `element.contents().length` instead of `element.children().length`. Children() returns all children _tag_ elements. Contents() returns all children _tag_ elements **plus** all node_text. Example: `$('
    hello
    ').children().length` returns 0, while `$('
    hello
    ').contents().length` returns 1.
    – Jose Rui Santos May 05 '15 at 18:22
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.

cletus
  • 616,129
  • 168
  • 910
  • 942
0

You could check the .html() accessor to see if it returns an empty string. Though this will return true on <p></p> but I'd imaging for all intents and purposes that could be treated as a self closing tag.

Spencer Ruport
  • 34,865
  • 12
  • 85
  • 147