Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternative to innerHTML

I kind of feel like I'm abusing the DOM with my code...

for(var i=0; i<json.length; ++i){       
    var newobj = document.createElement("div");
    var inner = "<img src='"+json[i].picture+"' alt='Item preview' class='icon' />";

    inner += "<p>"+json[i].id+"<br />qty:"+json[i].qty;
    inner += "<a href=\"javascript:clearProduct('"+json[i].id+"')\">";
    inner += "<img alt='Seperator' src='images/form-sep.gif' />";
    inner += "<img src='images/cross.png' alt='Remove this item.' title='Remove this item.' />";
    inner += "</a></p>";
    newobj.innerHTML = inner;
    newobj.className = "cart_item";
    $('cartitems').appendChild(newobj);
    $('cartcount').innerHTML = json.length;
}

Is there a better way to do this? I mean, yes I could through and use createElement for each element and setting each attribute separately but that seems like a lot just when this is so simple. Is there a better way?

like image 536
MackDaddy Avatar asked Feb 21 '26 20:02

MackDaddy


1 Answers

I like to create a nice element-creation interface; something like this:

function el( name, attrs ) {

    var elem = document.createElement(name),
        styles = attrs.style;

    for (var prop in styles) {
        try {
            elem.style[prop] = styles[prop];
        } catch(e) {}
    }

    for (var attr in attrs) {
        if (attr === 'style') { continue; }
        elem[attr] = attrs[attr];
    }

    return elem;

}


var myImage = el('img', {
    src: '/path/to/image.jpg',
    alt: 'Really cool image',
    style: {
        border: '1px solid red',
        padding: '10px'
    }
});
like image 110
James Avatar answered Feb 24 '26 10:02

James