cHTML - Small frame work for creating html w/ javascript
Platform: Javascript
Published May 05, 2012
Updated May 05, 2012
cHTML About:
A small framework to make html creation a little easier. It uses 'member-stringing' so you can make consecutive member calls on a cEle object
cHTML Usage:
cHTML(ele as string|
Element) -> Returns a cEle Object
If
ele is a string and begins with "#", cHTML will retrieve the element by the id.
If
ele is a string and doesn't begin with "#", an element will be created using
ele as the type
If
ele is an Element Object, the specified element will be used.
cEle Object:
.ele() -> returns the current working element
.set(attr as object) -> sets the specified element attributes.
Where
attr is an object formated as such:
{ attr : value, attr : value, ... }
.text(text as string) -> appends the specified text to the element
.html(html as string,
overwrite as boolen) -> appends the specified html to the working element.
If
overwrite is true, the innerHTML is overwritten.
.attach(method as string,
ele as Element) -> appends the working element to the specified element.
Method can be "
to", "
before" or "
after"
.on(event as string,
func as function,
bubble as boolean) -> adds an event handler for the specified event.
window.cHTML = function (ele) {
function cEle(ele) {
this._ele = ele;
this.ele = function(){
return this._ele
}
this.set = function (param) {
for (var attr in param) {
if (param.hasOwnProperty(attr)) {
this._ele.setAttribute(attr,param[attr])
}
}
return this
}
this.text = function(text){
this._ele.appendChild(document.createTextNode(text))
return this
}
this.html = function(text,overwrite){
if (overwrite){
this._ele.innerHTML=text
}
else {
this._ele.innerHTML+=text
}
return this
}
this.attach = function (method,ele) {
if (typeof ele == 'string') {
ele = document.getElementById(ele)
}
if (!(ele instanceof Node)){
throw "Invalid attachment element specified"
}
else if (!/^(?:to|before|after)$/i.test(method)){
throw "Invalid append method specified"
}
else if (method == 'to'){
ele.appendChild(this._ele)
}
else if (method == 'before'){
ele.parentNode.insertBefore(this._ele,ele)
}
else if (typeof ele.nextSibling == 'undefined'){
ele.parentNode.appendChild(this._ele)
}
else {
ele.parentNode.insertBefore(this._ele,ele.nextSibling)
}
return this;
}
this.on=function(event,func,bubble){
if (this._ele.addEventListener) {
this._ele.addEventListener(event,func,bubble);
}
else if (this._ele.attachEvent) {
this._ele.attachEvent("on" + event,func);
}
return this;
}
}
if (typeof ele == "string"){
ele = /^#/i.test(ele) ? document.getElementById(ele.substring(1)) : document.createElement(ele)
}
if (ele instanceof Node){
return new cEle(ele)
}
else {
throw "Invalid element type specified"
}
}