Javscript: Creating a self-closing img tag with createElement?

Tarzan

New Member
Messages
66
Reaction score
0
Points
0
Hi!
I'm trying to create a img tag dynamically with javascript. So far I've used the createElement function.
The problem is however that the created tag seems to be open:
Code:
<img src="target">
Is there a way to create a self-closing img tag?
Code:
<img src="target" />
I would prefer not to use .innerHTML since I want the img to become part of the DOM tree (and looks cleaner :) )
 

essellar

Community Advocate
Community Support
Messages
3,295
Reaction score
227
Points
63
If you are working against an HTML (as opposed to XHTML) DOM, there is no need to explicitly close a unary tag (like <img>, <hr> or <br>). The HTML does not appear in the source in any case; it only exists in the modified DOM (which may be accessible using something like View Rendered Source, the developers' toolkit or a debugger). Since what you are seeing is not source code but an HTML rendering of the DOM as it exists in memory, the viewer will render whatever the valid representation of that element happens to be. Strictly speaking, the slash at the end of a unary tag in an HTML document is an illegal garbage character, even if it is required in XHTML (which is a dialect of XML that only superficially resembles HTML).
 
Top