I am following a code to make a quiz. I am building a function to highlight one list item and add a class to it.
JavaScript
x
10
10
1
function chooseAnswer(){
2
answer.querySelectorAll('li').forEach((option)=> {
3
option.addEventListener('click',()=>{
4
if(answer.querySelector('.selected')){
5
let activeAnswer=answer.querySelector('.selected');
6
activeAnswer.classList.remove('selected')
7
}else
8
option.classList.add('selected')
9
})
10
The code is working but i do not understand the if condition from the source. Can someone help?
Advertisement
Answer
answer.querySelector('.selected')
will return the element with .selected
class if it exists within the answer element.
If there is no .selected
class within the answer element, it will return null
.
In this code:
JavaScript
1
5
1
if(answer.querySelector('.selected')){
2
---
3
}else
4
option.classList.add('selected')
5
If the if
condition is null
that means there was no .selected
element found. So the else block gets executed and it adds a .selected
class to option.
But if there was a .selected
class inside the answer element, the if
condition would be truthy and would execute. Removing the .selected
class.