Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
103 views
in Technique[技术] by (71.8m points)

javascript - How to apply eventListener to all input className

I want to add EventListener to all input className that will disable space when typing using oninput.

input class="inputX" id="idA"></input>
input class="inputX" id="idB"></input>
input class="inputX" id="idC"></input>
input class="inputX" id="idD"></input>

Im using FOR statement and still nowhere. It can be done if im using getElementById but not with getElementsByClassName/Name and even with querySelectorAll (which I believe there is some code missing).

I found JQuery code but I dont know how to write it back in Javascript.

$(".inputX").keyup(function() {
    $(this).val($(this).val().replace(/s/g, ""));

Hope someone can help me out ~ Thanks

Manage to disable space when using getElementById (as below), but how to use getElementsByClassName?

document.getElementById("idA").addEventListener("input", myFunction);

function myFunction() {
  var x = document.getElementById("idA");
  x.value = x.value.replace(/s/g, "");
}  
<input class="inputX" id="idA"></input><br />
<input class="inputX" id="idB"></input><br />
<input class="inputX" id="idC"></input><br />
<input class="inputX" id="idD"></input><br />
question from:https://stackoverflow.com/questions/66060497/how-to-apply-eventlistener-to-all-input-classname

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

First you need to understand the difference between getElementsByClassName and querySelectorAll. First one creates HTMLCollection[] while latter one creates a NodeList[].

HTMLCollection[] cannot be iterated with forEach while NodeList[] can:

const withClassName = document.getElementsByClassName('foo');
const withQuerySelector = document.querySelectorAll('.foo');

console.log(withClassName.forEach);
console.log(withQuerySelector.forEach);
<div class='foo'></div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...