0

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.

Hubert Kubiak
  • 607
  • 1
  • 7
  • 30
  • 2
    ["What is the scope of variables in JavaScript?"](https://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript) – Turnip Sep 24 '19 at 14:30

2 Answers2

2

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>
crenshaw-dev
  • 7,504
  • 3
  • 45
  • 81
1

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);
    }
}
James Whiteley
  • 3,363
  • 1
  • 19
  • 46
  • 1
    Or as [Michael's answer](https://stackoverflow.com/a/58082577/8230810) states, you don't need to declare the `parent` variable onload at all. Unless this is a simplified version of your actual use-case, where you do need to declare stuff like that onload. – James Whiteley Sep 24 '19 at 14:35