Reputation: 13
I'm currently working on my homework. I need to delete "ol" from the list using a button with javascript.
I've tried to using a div for all the children and a div for each but doesn't seem to work.
There's my script:
window.onload = function() {
const parent = document.querySelector('ul');
}
function supprime() {
parent.removeChild(parent.lastElementChild);
}
and my html...
<ul>
<ol>Item</ol>
<ol>Item</ol>
<ol>Item</ol>
<ol>Item</ol>
</ul>
<button onclick='supprime()'>DELETE</button>
The console log doesn't show any error.
Upvotes: 0
Views: 51
Reputation: 8392
Because parent
is declared with const
, it is scoped to the anonymous function attached to onload
. In the context of the supprime
function, typeof parent === 'undefined'
.
One fix would be to move the declaration of parent
outside the two functions and make it variable with let
. (See James' answer.)
Another fix would be to move const parent = document.querySelector('ul')
inside supprime
.
window.onload = function() {
// This `parent` won't be used in `supprime`, because `const` scopes it to this function.
const parent = 'nothing';
}
function supprime() {
const parent = document.querySelector('ul');
parent.removeChild(parent.lastElementChild);
}
<ul>
<ol>Item</ol>
<ol>Item</ol>
<ol>Item</ol>
<ol>Item</ol>
</ul>
<button onclick='supprime()'>DELETE</button>
Upvotes: 2
Reputation: 3474
You are declaring a variable inside the function function() { const parent = document.querySelector('ul'); }
and then throwing it away - this variable is out of scope to the function supprime()
. Read up on scopes.
This modification of your code will work - declare the variable in a place both functions can access it and just modify it when window.onload
is called:
let parent;
window.onload = function() {
parent = document.querySelector('ul');
}
function supprime() {
parent.removeChild(parent.lastElementChild);
}
<ul>
<ol>Item</ol>
<ol>Item</ol>
<ol>Item</ol>
<ol>Item</ol>
</ul>
<button onclick='supprime()'>DELETE</button>
Though you still need to handle when the list is empty, otherwise your button function will throw an error. Something like this would get around that:
function supprime() {
if(parent.children.length !== 0) {
parent.removeChild(parent.lastElementChild);
}
}
Upvotes: 1