How to Close ≪Img≫ Tag Properly

How to close img tag properly?

<img src='stackoverflow.png' />

Works fine and closes the tag properly. Best to add the alt attribute for people that are visually impaired.

Why is the img tag not closed in HTML?

Historically, HTML has been based on SGML which allows tags to be omitted under certain conditions.

Since the <img> element cannot have any child nodes, it is defined as EMPTY and the end tag is forbidden (as it would serve no purpose).

XHTML is HTML expressed in XML, and XML does not support optional or forbidden tags (although it allows a self-closing tag to substitute for a start+end tag pair), so it has to be explicitly closed there.

HTML 5 is backwards compatible with versions of HTML that were SGML based.

Syntax of img tag

img tag is a self-closing tag so it's a good practice to write it like <img /> (more XHTML style) although it's absolutely fine and valid to leave it without that slash.

Close all HTML unclosed IMG tags

(<img[^>]+)(?<!/)>

will match an img tag that is not properly closed. It requires that the regex flavor you're using supports lookbehind (which Ruby and JavaScript don't but most others do). Backreference no. 1 will contain the match, so if you search for this regex and replace by \1/> you should be good to go.

If you need to account for the possibility of > inside attributes, you could use

(<img("[^"]*"|[^>])+)(?<!/)>

This will match, e.g.,

<img src="image.gif" alt="hey, look--->">
<img src="image/image.gif">

and leave

<img src="image/image.gif" />

alone.

javascript regex - add closing img tag

myInput ='<img class="example1" src="/images/example1.png">';
myInput += '<img class="example2" src="/images/example2.png"/>';

result = myInput.replace(/(<img("[^"]*"|[^\/">])*)>/gi, "$1/>");

Explanation of the regex:

<img The start

"[^"]*" A string inside the tag. May contain the / character.

[^\/">] Anything else (not a string, not a / and not the end of the tag)

> The end of an IMG tag

This will only match unfinished tags, and will replace it by the whole thing, plus a />

As I said before this is NOT bulletproof, probably there is no regex that would work 100%.

Losing closing img tag with jQuery's .html() method

The problem (actually it's a safe-guard and a benefit) is that JavaScript, and therefore jQuery, creates only valid HTML. As the img tag has no closing tag (since it can't have any content, it self-closes) it isn't appended to the web-page.

References:

  • img element, Mozilla Developer Network.


Related Topics



Leave a reply



Submit