My question is rather elementary, but I do not understand why, in the following code, on button click only button dissapears, instead of the whole div:
<script>
function remove(id) {
//get the element node
element = document.getElementById(id);
//remove the element from the document
document.removeChild(element);
}
</script>
<div id="intro" class="jumbotron">
<h1>Your Offline Web Dictionary!</h1>
<p class="lead">
<div class="controls">
<input class="span7 " type="text" placeholder=" " name="key">
</div>
<div>
<button class="btn btn-large btn-success" onclick="remove(intro)">
Dictionary Search
</button>
</div>
</div>
JSFiddle
In JavaScript, an element can only be deleted from its parent. To delete one, you have to get the element, find its parent, and delete it using the removeChild method.
The JavaScript “remove()” method is used for deleting the specified HTML element from the Document Object Model (DOM).
Removing an element using the removeChild() method First, select the target element that you want to remove using DOM methods such as querySelector() . Then, select the parent element of the target element and use the removeChild() method.
Remove an element at any index with splice You can remove the element at any index by using the splice method. If you have an array named arr it can be used in this way to remove an element at any index: arr. splice(n, 1) , with n being the index of the element to remove. The splice method can accept many arguments.
The problem is that the button element has a remove property so that is called instead of your remove function. And also the string thing.
<button class="btn btn-large btn-success" onclick="window.remove('intro');console.log(this.remove);">
Search
</button>
http://jsfiddle.net/HMEVd/76/
Two problems. Firstly, intro
should be a string, not an identifier, so use remove('intro')
in your onclick.
Second, document.rwmoveChild
is incorrect. removeChild
should be called on the parent of the element you are removing. It is common to use:
element.parentNode.removeChild(element);
intro
should be sent to the function as a string rather than a variable, i.e, 'intro'
Also, you must rename your function, for example, removeById
instead of remove
. Then it works perfectly.
The function remove
actually does something completely different. (Your function is not even invoked when it is named remove
as you can see by putting an alert message into it.)
function removeById(id) {
//get the element node
element = document.getElementById(id);
//remove the element from the document
document.removeChild(element);
}
...
<button class="btn btn-large btn-success" onclick="removeById('intro')">
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With