PDA

View Full Version : Remove on click



d-machine
08-29-2008, 10:20 PM
Hi I have a simple code for adding and removing elements.
My problem is that I need only to have the option to remove elements and it should onload print me 5 elements (and not include the option to add more..)

Thanks in advanced



<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>ADD N REMOVE</title>
<script 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 = 'Remove This Element (' + ++i + ')';
Dom.add(el, 'content');
Event.add(el, 'click', function(e) {
Dom.remove(this);
});
});
});
</script>
</head>

<body>
<div id="doc">
<h1>Add &amp; Remove Elements with JavaScript</h1>
<p id="add-element">Add Elements</p>
<div id="content"></div>
</div>
</body>
</html>

rangana
08-30-2008, 02:37 AM
Change this part:


Event.add(window, 'load', function() {
var i = 0;
Event.add('add-element', 'click', function() {
var el = document.createElement('p');
el.innerHTML = 'Remove This Element (' + ++i + ')';
Dom.add(el, 'content');
Event.add(el, 'click', function(e) {
Dom.remove(this);
});
});
});


to:


Event.add(window, 'load', function() {
var i = 0;
for(var n=1;n<=5;n++){
var el = document.createElement('p');
el.innerHTML = 'Remove This Element (' + ++i + ')';
Dom.add(el, 'content');
Event.add(el, 'click', function(e) {
Dom.remove(this);
});
}
});