سؤال

I've got a pretty complicated DOM structure already and I'd like to eliminate the possibility of unterminated image elements causing issues.

Looking at the simplest case:

var prettyPicture = document.createElement("img");
//Add properties...
container.appendChild(prettyPicture );

Works fine, but when I insepct the dom I see the img element without a terminating slash such as <img/>

<img id="iamge-6816177" src="_site/images/detail/6816177.png">

No issues in the simple layout view, but when I look at a view with tons of these elements, random ones, even similar images within the same parent nodes do not render, though their nodes are in the dom inspector. Would missing termination cause any issues with the tree?

هل كانت مفيدة؟

المحلول

The closing tag of an img element is entirely optional - this won't cause you problems in any browser. So much so, in fact, that in HTML5 you're now not supposed to include the /> in img elements at all.

Also, what you see when you inspect the DOM is just how your inspector chooses to display elements with no closing tag - you can be sure that createElement() and appendChild() are generating valid HTML, as you're working directly with the DOM rather than providing text for the browser to parse into DOM objects.

نصائح أخرى

If you're concerned about

<img id="iamge-6816177" src="_site/images/detail/6816177.png">

instead of

<img id="iamge-6816177" src="_site/images/detail/6816177.png"/>

then there is no worry : the days of the painful XHTML have ended and HTML5 confirms that you shouldn't write XML-style self-closing tags.

From the spec :

Void elements only have a start tag; end tags must not be specified for void elements.

[...]

Void elements

area, base, br, col, command, embed, hr, img, input, keygen, link, meta, param, source, track, wbr

It's bad practice to clutter your code with ending tags. HTML isn't XHTML.

From http://www.w3schools.com/tags/tag_IMG.asp

In HTML the <img> tag has no end tag.

In XHTML the <img> tag must be properly closed.

In all cases, the browser won't care.

No this should not cause any issues. I would just ignore it as this will not harm w3.org compliance because DOM elements are generated dynamically.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top