ditto
ditto

Reputation: 6277

Add class to parent on focusin

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.

http://jsfiddle.net/58ddtbm9/

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

Answers (2)

dhouty
dhouty

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

Andy Ray
Andy Ray

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

Related Questions