javascript - JS - disable all inputs with className == "A" - Stack Overflow

On a web site I want to disable (lock) all inputs with className == "A". The inputs have mult

On a web site I want to disable (lock) all inputs with className == "A". The inputs have multiple classNames like "A B C":

This is the HTML

<input type="text" class="A B C" value="anything"/>

This is my JavaScript :

var el = document.getElementsByTagName("INPUT") 

for (var i = 0; i < el.length; i++) {
      if (el[i].className == 'A')   
          el[i].disabled = true
}

But this does not work because el.className is always "A B C". I know that I can use string methods to find A.

Are there more clever, faster ways ?

Info :
I need to use document.getElementsByTagName("INPUT") and I use pure JavaScript !

On a web site I want to disable (lock) all inputs with className == "A". The inputs have multiple classNames like "A B C":

This is the HTML

<input type="text" class="A B C" value="anything"/>

This is my JavaScript :

var el = document.getElementsByTagName("INPUT") 

for (var i = 0; i < el.length; i++) {
      if (el[i].className == 'A')   
          el[i].disabled = true
}

But this does not work because el.className is always "A B C". I know that I can use string methods to find A.

Are there more clever, faster ways ?

Info :
I need to use document.getElementsByTagName("INPUT") and I use pure JavaScript !

Share Improve this question edited Dec 22, 2016 at 16:48 j08691 208k32 gold badges269 silver badges280 bronze badges asked Dec 22, 2016 at 16:46 BenBen 6875 silver badges20 bronze badges 4
  • 5 Use document.querySelectorAll('input.A');, iterate over it and disable each element. – Tushar Commented Dec 22, 2016 at 16:47
  • 1 document.getElementsByClassName('A') is what you want to use instead of getElementsByTagName – Will P. Commented Dec 22, 2016 at 16:48
  • 1 Alternatively, consider using if(el[i].classList.contains("A")) – Niet the Dark Absol Commented Dec 22, 2016 at 16:49
  • classList would be better than className: developer.mozilla/en-US/docs/Web/API/Element/classList – Reinstate Monica -- notmaynard Commented Dec 22, 2016 at 16:50
Add a ment  | 

2 Answers 2

Reset to default 4

You can use document.querySelectorAll method which accepts CSS selectors:

document.querySelectorAll('input.A');

Expanding on from @undefined's answer, you could use querySelectorAll() on the specific class you're looking for scoped with input.

Complete code es6:

const inputs = document.querySelectorAll('input.A');
inputs.forEach(input => input.disabled = true);

Complete code es5:

var inputs = document.querySelectorAll('input.A');

for (var i = 0; i < inputs.length; i++) {
  inputs[i].disabled = true;
}

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745170654a4614904.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信