String processing to add trailing slashes to self-closing tags (IMG, BR, etc.)

If I get an element innerHTML element, some child elements must have a trailing slash, which must be valid XHTML (for example, "<br />"), but in Chrome Firefox they are missing or IE, regardless of the type of doctype.

Obviously, this does not really matter in most cases, but in my case I use pulling html from the DOM as part of the template system - so if these backslashes are missing, they go this way to the resulting page built using these templates, and This page will not be validated as XHTML because of this. And the non-checking pages seem to make my client sad.

So ... I am looking for javascript code (possibly a regex) that will add this backslash where necessary. If this worked for these types of elements that were good enough for me:

area, base, br, col, embed, hr, img, input, link, meta, param

I suggest that it should not be confused if there is> in quotation marks inside the tag.

I know that there is a dom-to-xml library (http://xhtmljs.codeplex.com/) that does this, but it also does a lot of other things and is pretty brute force. I hope for something a lot easier.

edit:

Well, since I didn't get any bites when approaching string processing, I went ahead and did what the trick does for me. (although this will be confused using> in quotation marks, which I will discuss later):

var addClosingSlashes = function (htmlString) { var elemTypes = [ "area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "param"]; var inString, outString = htmlString; for (var i=0; i<elemTypes.length; i++) { var index1 = 0, index2; inString = outString; outString = ''; while ((index1 = inString.indexOf("<" + elemTypes[i])) != -1) { if ((index2 = inString.indexOf(">", index1)) != -1 && inString.substring(index2 - 1, index2 + 1) != '/>') { outString += inString.substring(0, index2) + " />"; inString = inString.substring(index2+1); } else { break; } } outString += inString; } return outString; }; 
+4
source share
2 answers

If this is not server-side javascript, this will do nothing. By the time the browser runs javascript, the DOM is created as a DOM, and not as some text element. That is, the elements will already be embedded in the tree, and you can’t do anything to affect the rendering.

+1
source

Try changing the way the original document is submitted in response to this question: When objects (for example, the img tag) are created by javascript, it does not have a closing tag, How do I make it W3C valid?

Also, see the answer to this question ... :-) Open RegEx tags, with the exception of XHTML tags that are offline

+1
source

All Articles