Yong
Yong

Reputation: 41

How do I select multiple elements of same type but different classes?

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!

Upvotes: 0

Views: 605

Answers (2)

Luís Ramalho
Luís Ramalho

Reputation: 10208

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>

Upvotes: 0

messerbill
messerbill

Reputation: 5629

You an simply select by tag name:

const elements = document.getElementsByTagName("input")

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

Upvotes: 1

Related Questions