Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

string processing to add trailing slash to self-closing tags (IMG, BR etc)

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;
    };
like image 939
rob Avatar asked Nov 13 '22 20:11

rob


1 Answers

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.

like image 69
Stefan Kendall Avatar answered Nov 17 '22 00:11

Stefan Kendall