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
.
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
.
2 Answers
Reset to default 6There 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); } );
}
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 :)
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745347656a4623636.html
评论列表(0条)