Posted By

jatkins on 01/22/11


Tagged

element html DOM attribute childnodes


Versions (?)

HTML element generator


 / 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.

  1. function generateElement(elementType, attributes, childrenToAppend, innerHTML) {
  2. var i, isIE = navigator.appName == 'Microsoft Internet Explorer';
  3. if(isIE)
  4. tagCode = '<' + elementType;
  5. else
  6. newElement = document.createElement(elementType);
  7. if(attributes!=null) {
  8. for(i=0;i<attributes.length;i++) {
  9. if(attributes[i]) {
  10. if(isIE)
  11. tagCode += ' ' + attributes[i][0] + '="' + attributes[i][1] + '"';
  12. else
  13. newElement.setAttribute(attributes[i][0], attributes[i][1]);
  14. }
  15. }
  16. }
  17. if(isIE)
  18. newElement = document.createElement(tagCode + '>');
  19. if(childrenToAppend!=null) {
  20. for(i=0;i<childrenToAppend.length;i++) {
  21. newElement.appendChild(childrenToAppend[i]);
  22. }
  23. }
  24. if(innerHTML)
  25. newElement.innerHTML = innerHTML;
  26. return newElement;
  27. }

Report this snippet  

You need to login to post a comment.