View Full Version : document.createHTMLElement()

03-21-2003, 11:47 PM
Well, while working on a recent project (http://www.peterbailey.net/dhtml/taeditor.htm), I created a method for making DOM-approved™ HTML elements fairly easily. Here's the method
document.createHTMLElement = function( elemName, attribs )
var elem = document.createElement( elemName );
if ( typeof attribs != 'undefined' )
for ( var i in attribs )
switch ( true )
case ( i == 'text' ) : elem.appendChild( document.createTextNode( attribs[i] ) ); break;
case ( i == 'class' ) : elem.className = attribs[i]; break;
default : elem.setAttribute( i, '' ); elem[i] = attribs[i];
return elem;
}I also cooked up a little demo (http://www.peterbailey.net/test/createHTMLElement.htm) or two (http://www.peterbailey.net/test/createHTMLElement2.htm)

To use this, you will need to be familiar with object literals (http://devedge.netscape.com/library/manuals/2000/javascript/1.5/guide/ident.html#1009450)

Alex Vincent
03-22-2003, 01:13 AM
If the document is XHTML, you'll need to use createElementNS("http://www.w3.org/1999/xhtml", elemName) for the element. Fortunately, you shouldn't use the namespaced-attribute methods as well.

03-23-2003, 05:19 AM
Which, with all due respect, I think should be split so that comments regarding my post are easier to find, and so that all the other good information here isn't buried osbcurely in the "Post a Javascript" forum. :D

03-23-2003, 06:15 AM
*performs the first-ever thread split of CodingForums*


To quote Invader Zim, "Feel honored!"