Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

create pre-styled/populated DOM elements (See related posts)

/*
 * create a new DOM element with (optionally) specified className, CSS and text/html content
 * if text contains any markup, it's used as innerHTML value - else a child text node is attached
 * if there's also a parent node given, the new element will be appended as child node
 */
function createStyledElement(tag, parent, cls, css, txt) {
    var el = document.createElement(tag);
    if(cls) el.className = cls;
    if(css) for(var s in css) el.style[s]=css[s];
    if(txt) {
        if (txt.indexOf('<')!=-1) el.innerHTML=txt;
        else el.appendChild(document.createTextNode(txt));
    }
    if(parent) parent.appendChild(el);
    return el;
}

// usage example...
// 1st define some style params
var style1={
    background: '#def',
    color: '#f00',
    padding: '0.5em',
    border: '1px black dotted'
};

createStyledElement(
  'div',
  document.getElementsByTagName('body').item(0),
  null,
  style1,
  'hello <em>world</em>!'
);

Comments on this post

mrclay posts on Mar 25, 2006 at 20:06
Convenient function! I'd only make the test for HTML more rigorous and escape '<' and '>' so this can be used in a bookmarklet:
if (txt.match(/\u003C\S+.*\u003E/)) el.innerHTML = txt;
shaid posts on Sep 13, 2007 at 14:12
useful, will I be able to use it within selected words in a text?
BBV

You need to create an account or log in to post comments to this site.


Click here to browse all 5140 code snippets

Related Posts