Reputation: 6277
I want to add the class name active to the parent <label>
of this
. Can't figure out why it's only targeting the first input. No jQuery.
document.querySelector('.contact input, .contact textarea').addEventListener("focusin", function () {
this.classList.add('active');;
});
document.querySelector('.contact input, .contact textarea').addEventListener("focusout", function () {
this.classList.remove('active');;
});
Upvotes: 0
Views: 83
Reputation: 1989
querySelector
only returns the first match so you need querySelectorAll
instead. Here is an updated version of your fiddle.
And here is the modified JavaScript:
var inputs = document.querySelectorAll('.contact input, .contact textarea');
for (var i = 0; i < inputs.length; i++) {
inputs[i].addEventListener('focusin', function() {
this.classList.add('active');
});
inputs[i].addEventListener('focusout', function() {
this.classList.remove('active');
});
}
Upvotes: 1
Reputation: 32066
You have to use querySelectorAll
and then loop over each result and add an event to each element. querySelector
only returns the first match.
Upvotes: 0