How do I select multiple elements of same tag but different classes? Using vanilla JS

萝らか妹 提交于 2020-05-09 16:23:05

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!