Template Tag Polyfill for Internet Explorer

Template Tag Polyfill for Internet Explorer

Have you used the HTML5 template tag? I have too. Seems like a really great idea, until. until QA tests your project and you realize it won’t work in IE. Better yet, not just IE 7 or 8, all versions of IE. Super bummer.

It turns out that IE will allow you to select a template tags but it doesn’t provide an .content property for them. Something like $(‘template’)[0].content fails in IE. This turns out to be a real kick in the junk, so I came up with this polyfill. The idea is that you and a method to the documents Element.prototype that checks for the existence of the .content property, in the event it’s not there override it. All subsequent template tag calls will have .content in IE

Feel free to use, modify, update, or let me know where I’m intellectually lacking:

  Element.prototype.contentTest = function(){ 
 
      return function( element ){ 
 
         if(element.content){
             return element.content;
         }
 
         var elPlate= element,
             qContent,
             docContent;
 
             qContent = elPlate.childNodes;           
             docContent = document.createDocumentFragment();
 
             while(qContent[0]) {
                docContent.appendChild(qContent[0]);
             }
 
             elPlate.content = docContent;
             return  docContent; 
 
       }(this);
 
  }
 
  //get the templates contents
  var template = $('template')[0],
      templateContents = template.contentTest();
 
  //all subsequent calls to .content or .contentTest() will return the templates contents
This entry was posted in Uncategorized. Bookmark the permalink.