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(ele as string|Element)
: Returns a cEle Object
If
ele
is a string and begins with#
, cHTML will retrieve the element by the id.
Ifele
is a string and doesn't begin with#
, an element will be created usingele
as the type
Ifele
is an Element Object, the specified element will be used.
.ele()
-> returns the current working element
.set(attr as object)
: sets the specified element attributes.
Where
attr
is an object formated as{ 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 beto
,before
orafter
.on(event as string, func as function, bubble as boolean)
: adds an event handler for the specified event.
//cHTML Example:
var mydiv = cHTML("div").set({
"id" : "myDiv",
"class" : "mydiv",
"style" : "background-color: blue"
}).html("<b>My Html</b><br>",false).on("click",function(){
alert("mydiv was clicked!");
},false).attach("to",cHTML("#OtherDiv").set({
"style" : "background-color: blue"
}).ele());
mydiv.ele().style.fontWeight = "bold";
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"
}
}