How do I select multiple elements of same tag but

2020-05-01 06:50发布

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!

2条回答
ゆ 、 Hurt°
2楼-- · 2020-05-01 06:55

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>

查看更多
小情绪 Triste *
3楼-- · 2020-05-01 07:17

You an simply select by tag name:

const elements = document.getElementsByTagName("input")

https://developer.mozilla.org/en-US/docs/Web/API/Element/getElementsByTagName

查看更多
登录 后发表回答