问题
I have 6 inputs in a form, each with a class of .first .second .third .fourth .fifth .sixth respectively and I'd like to select them with vanilla JS but after trying with getElementsByClassName and querySelectorAll, it still didn't work out.
here is my line of code:
document.querySelectorAll("form input")[0].value==""
How do I select all the elements with those classes?
Thanks in advance for any help rendered!
回答1:
Your current code document.querySelectorAll("form input")
is basically getting what you want. However, you then do [0].value==""
which is basically getting the first input and checking if it's value is empty. You could apply the class sand
to all the inputs doing something like:
function check() {
var listo = document.getElementsByTagName("input");
for (var i = 0; i < listo.length; i++) {
listo[i].classList.add("sand");
}
for (let input of listo) {
input.setAttribute("required", "");
input.required = true;
}
console.log(listo[0]);
}
sandify.onclick = check;
input {
margin: 5px 0;
}
input.sand {
border: 1px solid sandybrown;
}
<form>
<input type="text" /><br/>
<input type="text" /><br/>
<input type="text" /><br/>
<input type="text" /><br/>
<input type="text" /><br/>
</form>
<button id="sandify">sandify</button>
回答2:
You an simply select by tag name:
const elements = document.getElementsByTagName("input")
https://developer.mozilla.org/en-US/docs/Web/API/Element/getElementsByTagName
来源:https://stackoverflow.com/questions/61171415/how-do-i-select-multiple-elements-of-same-tag-but-different-classes-using-vanil