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 !
-
5
Use
document.querySelectorAll('input.A');
, iterate over it anddisable
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 thanclassName
: developer.mozilla/en-US/docs/Web/API/Element/classList – Reinstate Monica -- notmaynard Commented Dec 22, 2016 at 16:50
2 Answers
Reset to default 4You 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条)