/ Published in: JavaScript
Released into the public domain. elementType is a string of the tag name (e.g. 'fieldset', 'div', etc.); attributes can be left null or is a multidimensional array of attributes (e.g. an onclick attribute resulting in alert(123); is passed as ['onclick', 'alert(123);']); childrenToAppend can be left null or is an array of already-created elements or an array of generateElement() calls; innerHTML can be left blank is a string containing the HTML to be placed inside the element. IE fix via http://www.sitepoint.com/forums/javascript-15/setattribute-not-working-ie-470313.html#post3345178.
Expand |
Embed | Plain Text
function generateElement(elementType, attributes, childrenToAppend, innerHTML) { var i, isIE = navigator.appName == 'Microsoft Internet Explorer'; if(isIE) tagCode = '<' + elementType; else newElement = document.createElement(elementType); if(attributes!=null) { for(i=0;i<attributes.length;i++) { if(attributes[i]) { if(isIE) tagCode += ' ' + attributes[i][0] + '="' + attributes[i][1] + '"'; else newElement.setAttribute(attributes[i][0], attributes[i][1]); } } } if(isIE) newElement = document.createElement(tagCode + '>'); if(childrenToAppend!=null) { for(i=0;i<childrenToAppend.length;i++) { newElement.appendChild(childrenToAppend[i]); } } if(innerHTML) newElement.innerHTML = innerHTML; return newElement; }
You need to login to post a comment.
