...

View Full Version : Javascript - How to remove div onClick



sea4me
05-11-2009, 04:06 AM
Hi! I would like my div to be deleted on click...

I have the code:

function deleteline()
{
this.parentNode.parentNode.removeChild( this.parentNode );
return false;
}

My HTML:

<div>
<input type="button" onclick="deleteline()" value="Remove this DIV" />
</div>
<div>
<input type="button" onclick="deleteline()" value="Remove this DIV" />
</div>
<div>
<input type="button" onclick="deleteline()" value="Remove this DIV" />
</div>

But it doesn't work:confused:

Any help would be VERY VERY appreciated! :)

itsallkizza
05-11-2009, 04:46 AM
Try


function deleteParentElement(n){
n.parentNode.parentNode.removeChild(n.parentNode);
}




<div>
<input type="button" onclick="deleteParentElement(this)" value="Remove this DIV" />
</div>

adios
05-11-2009, 07:39 AM
function deleteline()
{
this.parentNode.parentNode.removeChild( this.parentNode );
return false;
}

Inside that function, the this keyword refers to the object that the function (which is also an object) is a property of. Since you declared it with the function keyword, can you guess what that might be?



<html>
<head>
</head>
<body>
<script type="text/javascript">

function deleteline()
{
alert(this);
}
</script>
<div>
<input type="button" onclick="deleteline()" value="Who owns 'ya?" />
</div>
</body>
</html>


So, instead, as itsallkizza has done, you pass the this of the button object, which is the 'owning object' of the event handler (an anonymous function which calls 'deleteline'). Once it's 'inside' the function, you refer to it by its parameter variable - 'buttonObj' below - not this, which being context-sensitive, now points to a completely different object.



<html>
<head>
</head>
<body>
<script type="text/javascript">

function deleteline(buttonObj)
{
var node = buttonObj;
do
{
node = node.parentNode;
}
while
(node.nodeType != 1 && node.nodeName != 'div');
node.parentNode.removeChild(node);
}

</script>
<div>
<input type="button" onclick="deleteline(this)" value="Remove this 1st DIV" />
</div>
<br />
<div>
<input type="button" onclick="deleteline(this)" value="Remove this 2nd DIV" />
</div>
<br />
<div>
<input type="button" onclick="deleteline(this)" value="Remove this 3rd DIV" />
</div>
</body>
</html>


If you hardcode your moves around the DOM tree, any changes to the document - sometimes even just adding whitespace to the HTML - can break the script. Generally better to use 'smart' routines that actually look for the item in question (in this case, an object that is both a parent element and a div element as well). hth

http://www.howtocreate.co.uk/tutorials/javascript/dombasics
http://www.quirksmode.org/dom/intro.html
https://developer.mozilla.org/en/traversing_an_html_table_with_javascript_and_dom_interfaces

sea4me
05-11-2009, 11:06 PM
Thank you both!


Now I understand everything better!!! :)



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum