Skip to content

Instantly share code, notes, and snippets.

@composite
Last active December 10, 2015 23:08
Show Gist options
  • Save composite/4507324 to your computer and use it in GitHub Desktop.
Save composite/4507324 to your computer and use it in GitHub Desktop.
document.createElementWith - Create a prepared element with JSON. this method is currently not W3C Standard, but more convenient.
/*
usege :
document.createElementWith('button',{
attr:{type:'button'},
name:'mybutton',value:'myvalue',
style:{border:'1px solid red'},
init:function(){
this.onclick=function(){
alert('my button clicked.');
};
}
})
*/
document.createElementWith=function(tag,op){
tag=document.createElement(tag);
if(!op) return tag;
var s='style',a='attr';
for(var n in op){
if(n==s){
for(var m in op[s]) tag[s][m]=op[s][m];
}else if(n==a){
for(var m in op[a]) tag.setAttribute(m,op[a][m]);
}else if(n=='init'&&typeof(op[n])=='function'){
op[n].call(tag,op);
}else if(n=='type'){
tag.setAttribute(n,op[n]);
}else tag[n]=op[n];
}
return tag;
};
<!DOCTYPE html>
<html>
<head>
<meta charset="euc-kr">
<title>document.createElementWith TEST</title>
</head>
<body>
<form id="testform" method="get" action="">
<label>이름 : <input type="text" name="name"></label><br>
<label>나이 : <input type="number" name="age"></label><br>
<label>성별 : <select name="gender"><option value="M">남</option><option value="F">여</option></select></label><br>
<label>사진 : <input type="file" name="pic"></label><br>
<button type="submit">등록하기</button>
</form>
<script>
document.createElementWith=function(tag,op){
tag=document.createElement(tag);
var s='style';
for(var n in op){
if(n==s){
for(var m in op[s]) tag[s][m]=op[s][m];
}else if(n in tag) {
if(!n.indexOf('on')||typeof tag[n]!='function') tag[n]=op[n];
}else tag.setAttribute(n,op[n]);
}
return tag;
};
window.onload=function(){
document.getElementById('testform').appendChild(document.createElementWith('input',{
type:'text',name:'test',value:'tester',
style:{
border:'1px solid black',
color:'gray'
}
}));
};
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment