最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Use addEventListener on a class not working - Stack Overflow

programmeradmin2浏览0评论

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.

Share Improve this question edited Mar 15, 2023 at 9:37 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked Jul 15, 2015 at 13:36 William RudentWilliam Rudent 192 silver badges6 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 6

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); } );
}
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 :)

发布评论

评论列表(0)

  1. 暂无评论