If I 开发者_开发百科get the innerHTML of an element, certain child elements should have a trailing slash to be valid XHTML (for example, "<br />"), but they don't, in Chrome, Firefox or IE, regardless of the doctype.
Obviously this doesn't matter most of the time, but in my case I am using yanking out html from the DOM as part of a templating system -- so if those backslashes are missing, they go that way into the resulting page built using those templates, and that page won't validate as XHTML because of this. And non-validating pages seem to make my client sad.
So....I'm looking for some javascript code (maybe a regex) that will add that backslash where appropriate. If it worked for these element types that's good enough for me:
area, base, br, col, embed, hr, img, input, link, meta, param
I guess it has to not get confused if that there is a > in quotes within the tag.
I know there is an dom-to-xml library out there (http://xhtmljs.codeplex.com/) that does this, but it also does a lot of other things and is quite brute force. I'm hoping for something much simpler.
edit:
All right, since I didn't get any bites on the string processing approach, I went ahead and did something that does the trick for me. (although it would get confused by a > in quotes, which I'll deal with 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;
};
Unless this is server-side javascript, this won't do anything. By the time the browser executes javascript, the DOM is built as a DOM, and not as some kind of text element. That is, the elements will have been built into a tree already, and there's nothing more you can do to affect rendering.
Try changing the way the source document is served as per the answer in this question: When objects (e.g. img tag) is created by javascript, it doesn't have the closing tag. How do I make it W3C valid?
Also, please see the answer of this question... :-) RegEx match open tags except XHTML self-contained tags
精彩评论