William Rudent
William Rudent

Reputation: 19

Use addEventListener on a class not working

I am trying to convert my script using addEventListener with getElementById on a var for a getElementByClassName but this doesn't work. How to fix it?

See my code

JavaScript:

var input = document.getElementByClassName('myClass');

_slider.noUiSlider.on('update', function( values, handle ) {

    var value = values[handle];

    if ( handle ) {
        input.value = Math.round(value);
});

input.addEventListener('change', function(){
    _slider.noUiSlider.set([null, this.value]);
}, false);

HTML:

<input type="number" class="myClass">

This script work perfectly if I find my div with an ID, but not work with a CLASS.

Upvotes: 1

Views: 4181

Answers (2)

Sanjay M
Sanjay M

Reputation: 1

var input = document.getElementById('id_name')

...here addEventListener will work because "id" will unique but in case of "class" there might be same values entered...
So you have to select which element you want to manipulate...example ==>

var input = document.getElementsByClassName('class_name')[0] // after this addEventListener will work.

Hope this might help you :)

Upvotes: 0

epascarello
epascarello

Reputation: 207557

There is no getElementByClassName. There is getElementsByClassName that returns a collection. If there is only one, than select the first index.

var input = document.getElementsByClassName('myClass')[0];

Other option is querySelector

var input = document.querySelector('.myClass');

My guess is that you do not have just one element, but multiple, than you need to loop over the collection.

var inputs = document.getElementsByClassName('myClass');
//or
//var inputs = document.querySelectorAll('.myClass');
for( var i=0; i<inputs.length; i++){
    inputs[i].addEventListener("click", function() { console.log(this); } );
}

Upvotes: 6

Related Questions