我能够获取具有特定类名称的元素,但无法检索具有该特定类名称的元素数量的长度。
我应该如何获取具有子元素的特定类名的元素数量?
<强> jsFiddle
document.getElementById('contact').onsubmit = function() {
var children = this.children;
for(var i = 0; i < children.length; i++) {
if (children[i].className == 'req') {
console.log(children[i]); //defined
console.log(children[i].length); //undefined
}
}
return false;
};
最佳答案
我认为您想要计算该类的子元素数量:
document.getElementById('contact').onsubmit = function() {
var children = this.children;
var count = 0;
for(var i = 0; i < children.length; i++)
if (children[i].classList.contains('req'))
count++;
console.log(count+" of "+children.length+" have the class 'req'");
return false;
};
关于javascript - 获取具有特定类名的子元素的长度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18132549/