在javascript中查找具有相同自定义属性的元素数
我有一个多行的表,它有一个公共的自定义属性prId。如何查找具有相同自定义属性的行数。我不能使用jquery在javascript中查找具有相同自定义属性的元素数,javascript,Javascript,我有一个多行的表,它有一个公共的自定义属性prId。如何查找具有相同自定义属性的行数。我不能使用jquery <tr id="mainRow2" prId = "2"></tr> <tr id="subRow2_1" prId = "2"></tr> <tr id="subRow2_2" prId = "2"></tr> <tr id="subRow2_3" prId = "2"></tr> <
<tr id="mainRow2" prId = "2"></tr>
<tr id="subRow2_1" prId = "2"></tr>
<tr id="subRow2_2" prId = "2"></tr>
<tr id="subRow2_3" prId = "2"></tr>
<tr id="mainRow5" prId = "5"></tr>
<tr id="subRow5_1" prId = "5"></tr>
<tr id="subRow5_2" prId = "5"></tr>
<tr id="subRow5_3" prId = "5"></tr>
<tr id="subRow5_4" prId = "5"></tr>
试试:
工作:如上图所示,不使用查询选择器(更好,但支持较少),您可以使用
var trs = document.getElementsByTagName('tr'), tr, i, count = 0;
for (i = 0; ( tr = trs[i] ); i += 1) {
// use your own attribute value here, of course
if (tr.getAttribute('prId') === '2') {
count += 1;
}
}
alert(count + ' prIds counted.');
使用querySelectorAll()
var trs = document.getElementsByTagName('tr'), tr, i, count = 0;
for (i = 0; ( tr = trs[i] ); i += 1) {
// use your own attribute value here, of course
if (tr.getAttribute('prId') === '2') {
count += 1;
}
}
alert(count + ' prIds counted.');