Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
100 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 Answer

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...