Personal Information
Personal Information

Reputation: 581

how to construct a switch statement to run a function depending on if an element contains a particular class?

how do I convert the following to a switch statement?

if (event.target.classList.contains('ClassName')) {
    callFunction1()
} else if (event.target.classList.contains('anotherClassName')) {
    callFunction2()
}

where the html in question looks something like this:

<div class="ClassOne classTwo className"></div>
<div class="ClassThree classFour anotherClassName"></div>

I know this is incorrect but it gives an idea of what i'm trying to do.

switch (event.target) {
    case "className":
        function1(event.target)
        break
    case "anotherClassName":
        function2(event.target)
        break
}

Upvotes: 0

Views: 106

Answers (1)

Maximilian Ochs
Maximilian Ochs

Reputation: 141

You could do something like this:

switch (true) {
    case event.target.includes('className'):
        function1(event.target)
        break
    case event.target.includes('anotherClassName'):
        function2(event.target)
        break
}

But personally, I think that it is counter intuitive to use switch-statements this way. What's wrong with using if and else if in your case?

Upvotes: 1

Related Questions