dynamically create element using javascript
- by ajithperuva
I need to create textbox dynamically when user click a link.And also i need to remove that textbox according to user decission.I am trying the following script.
<script language="JavaScript" type="text/javascript">
var Dom = {
get: function(el) {
if (typeof el === 'string') {
return document.getElementById(el);
} else {
return el;
}
},
add: function(el, dest) {
var el = this.get(el);
var dest = this.get(dest);
dest.appendChild(el);
},
remove: function(el) {
var el = this.get(el);
el.parentNode.removeChild(el);
}
};
var Event = {
add: function() {
if (window.addEventListener) {
return function(el, type, fn) {
Dom.get(el).addEventListener(type, fn, false);
};
} else if (window.attachEvent) {
return function(el, type, fn) {
var f = function() {
fn.call(Dom.get(el), window.event);
};
Dom.get(el).attachEvent('on' + type, f);
};
}
}()
};
Event.add(window, 'load', function() {
var i = 0;
Event.add('add-element', 'click', function() {
var el = document.createElement('p');
el.innerHTML = '<br><input type="text">Remove(' + ++i + ')';
Dom.add(el, 'content');
Event.add(el, 'click', function(e) {
Dom.remove(this);
});
});
});
</script>
<style>
#add-element {
cursor: pointer;
}
</style>
<body>
<div id="doc">
<p id="add-element">Add Elements</p>
<div id="content"></div>
</div>
</body>
It will create element and remove the element.But, it not allow me to enter text in newly created textbox( if i need).What is wrong with me.Please help to go forward...please