Can you help about the JS DOM example below,
The if-else structure I specified in example 1 works, but the switch-case structure I specified in example 2 does not work. The switch-case structure does not work, although they both function the same. Why ?
Thanks
--- Example 1 / Works ---
fontSizes.forEach(size => {
size.addEventListener('click', () => {
if(size.classList.contains('font-size-1')) {
.....
} else if (size.classList.contains('font-size-2')) {
.....
}
})
})
--- Example 2 / Doesn't work ---
fontSizes.forEach(size => {
size.addEventListener('click', () => {
switch (size.classList.contains) {
case 'font-size-1':
....
break;
case 'font-size-2':
....
break;
}
})
})
Please not that they are not the same. In the first one you are calling function add taking the output whereas in the second one all you are passing via switch statement is the reference to function. The size.classlist.contains is a function which expects an argument. Please know the difference.
You didn't use the switch properly, you're checking size.classList.contains which points to a function with strings (like font-size-1) instead of comparing the actual value.
You can use split (with the includes functions) or use size.classList.contains in each case
Take a look here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes https://developer.mozilla.org/en-US/docs/Web/API/DOMTokenList/contains How to check className in a switch statement when an element has multiple classes
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