-1

[BEGINNER] I want to clear my list after clicking a button (which I managed to do) and I want to create an IF statement. IF the UL has LI's then clear list. If UL does not have LI's then I want to alert('List is already clear'). The code below doesnt work, I'm not sure what I'm doing wrong. Thank you for you help.

const clearBtn = document.querySelector('.clear-btn');
const list = document.querySelector('.list');
clearBtn.addEventListener('click', clearList);


function clearList() {
    if (list.hasChildNodes = true) {
        list.innerHTML = ''
    } else {
        alert('List is already clear');
    }
}

1 Answers1

0

Did you try in your condition to make a double equal , because it's a logical statement not a arithmetique one.

it will be like if(list.hasChildNodes == true){...}

Dharman
  • 30,962
  • 25
  • 85
  • 135
  • 1
    Note that `if (list.hasChildNodes === true)` would probably be even better, and for most situations `if (list.hasChildNodes)` would even be best. – Peter B Feb 18 '21 at 13:17
  • So I've tried the double and triple equals. When clicking on the clear button, the alert pops up in both cases. If the list has children or not. The "else" should be that the list has no children and the alert should only work in that case – philipHinch Feb 18 '21 at 14:08
  • Ok I got it. My logic was a bit wrong and I used "list.childElementCount" and the ===. Thank you! – philipHinch Feb 18 '21 at 15:21