Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Create Pre-styled/populated DOM Elements

DZone's Guide to

Create Pre-styled/populated DOM Elements

·
Free Resource

/*
 * 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 world!'
);
Topics:

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}