Code:
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?
Code:
<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.
Code:
<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/tutoria...ript/dombasics
http://www.quirksmode.org/dom/intro.html
https://developer.mozilla.org/en/tra...dom_interfaces