XHTML Element Closure



I ran into an XHTML element closure issue a couple of weeks ago and wanted to share it here. I had two div layers with a Google map in each. The markup basically looked like:

[div id="map1" /]
[div id="map2" /]

It doesn’t get much easier than that, but I ran into a big problem. I was unable to access the second map and do anything with it. After extensive diagnosis I randomly changed my markup to:

[div id="map1"][/div]
[div id="map2"][/div]

and that did the trick. Everything worked perfectly after that. I ran into this issue before, but never dug into the details to figure out what was really going on. Since I try to keep everything XHTML compliant I tried to make use of self-closing tags whenever I can. This is where I got burned.

After digging around I found out the basic rule of thumb is to self-close only if the tag doesn’t normally contain content. A few examples are:

[img xsrc="" mce_src="" /]
[br /]
[input type="hidden" /]

and so on. Since div elements generally contain content they need to have a matching end tag instead of using the short hand approach. This link is a good reference to understanding when and when not to self-close.



Leave a Reply