September 25, 2007
While playing around with the prototype framework, I wrote 2 code snipplets I want to share with you:
var _ = function(sEName, id, classname, attributes) {
var e = document.createElement(sEName);
if(id) { e.id = id; }
if(classname) { e.className = classname; }
if(attributes) { for(var p in attributes) { e.setAttribute(p, attributes[p]); } }
return $(e);
}
Element.addMethods({
_a: function(element, e) {
element.appendChild(e);
return $(e);
},
_r: function(element, e) {
element.removeChild(e);
return$(e);
}
});
Using the functions above, you will be able to create HTML structures on the fast DOM-lane:
var oHTML = _('div', 'head', 'headClass');
oHTML._a(_('div', 'second', 'secondClass'))._a(_('img', 'myimage', 'images', {src:'pica.jpg'}));
document.body.appendChild(oHTML);
Which results in:
<div id="head" class="headClass">
<div id="second" class="secondClass">
<img src="pica.jpg" id="myimage" class="images" />
</div>
</div>
Enjoy.
Add to: