You add a change event listener to the select, and when its value equals âcondition_2â, you add that class to the div:
var select = document.querySelector('select') // use more specific selector here
var classOne = document.querySelector('.classone')
select.addEventListener('change', function (event) {
if (event.target.value === 'condition_2') {
classOne.classList.add('newclass')
}
})
CSS associated with that class will of course apply then.
I mean you should give that select a unique class or an ID so that you can unambiguously query it⌠just "select" is pretty generic and itâs probably not the only one on your page.
That can be taken care of with css using the parent ânewclassâ. There is no need for the newclass also on the children unless you have some other structures?
Thereâs probably a more efficient way but you could loop through them like this:
var select = document.querySelector('select') // use more specific selector here
var classOne = document.querySelectorAll('.class1')
select.addEventListener('change', function(event) {
if (event.target.value === 'condition_2') {
for (i = 0; i < classOne.length; ++i) {
classOne[i].classList.add('newclass')
}
}
})
You iterate over the items in the node list, and add that class to each; you can do so with an old for loop, a for...of loop or using the .forEach() method. Unless you need to break out of a loop early, I would generally recommend using the latter:
var elements = document.querySelectorAll('.classone, .class1')
elements.forEach(function (element) {
element.classList.add('newclass')
})
There are some detailed examples as well as notes on browser compatibility in the MDN article on node lists.
Yes I noticed that IE11 doesnât support forEach which is why I went with the older loop method (Mind you I only knew that because I had to look it all up anyway).
This is a very good discussion. Perhaps I feel that the title is not the most suitable one. Can you please help me to change it to the most suitable title so that others can search it in the future.
Also, In this example â
var select = document.querySelector('select') // use more specific selector here
var classOne = document.querySelector('.classone')
select.addEventListener('change', function (event) {
if (event.target.value === 'condition_2') {
classOne.classList.add('newclass')
}
})
when we choose the condition 1 again the extra class that we are injecting should be deleted. How to accomplish this?
By default, I have selected condition 2, for example, but it doesnât work â I mean the class associated with that condition doesnât get implemented. I think we need to tie this to some script.