Currently the select.value gets only checked on change events, so you’d have to do this initially too:
var checkSelect = function () {
if (select.value === 'condition_2') {
classOne.classList.add('newclass')
} else {
classOne.classList.remove('newclass')
}
}
// Do the check initially...
checkSelect()
// ... and on change events
select.addEventListener('change', checkSelect)
Why where should there be curly braces? The first line is a regulare function call, in the second line that function gets passed to .addEventListener(). You’ll often see an anonymous function here, like in the previous examples…
select.addEventListener('change', function () {
// ...
})
… but you can just as well assign that function to a variable (so that it can be used elsewhere too), and then pass in that variable like any other argument.
EDIT: Sorry, missed it in the first post. We’ve suddenly changed from classOne to classTwo… is THAT defined? How is it defined? Are there more than one objects that have matched your selector?
Ok, but is there more than one thing on the page with the class “flex_parent”? The code… looks correct… but if the classTwo targetter is aiming at the wrong element, you may be changing the class of something you didnt mean to.
Again. I understand the idea. I understand the code.
You’re telling us the code doesnt work. We’re trying to find out why. Because it does work.
Is the div, and the definition of classTwo, the only times in your code the word “flex_parent” exists?
EDIT: Copy and paste your entire HTML, and we’ll diagnose the problem.
function checkSelect () {
var select = document.querySelector('select') // use more specific selector here
var classTwo = document.querySelector('.flex_parent')
if (event.target.value === 'con_2') {
classTwo.classList.add('flex_parent_2')
}else if (event.target.value === 'con_3') {
classTwo.classList.add('flex_parent_3')
}else if (event.target.value === 'cond_1') {
classTwo.classList.remove('flex_parent_3', 'flex_parent_2')
}
}
checkSelect()
select.addEventListener('change', checkSelect)