计算没有名称或 ID 的通用 DIV 标记

Count generic DIV tags with no name or ID

本文关键字:DIV 标记 ID 有名称 计算      更新时间:2023-09-26

如何使用javascript来计算DIV标签的数量?唯一的属性将永远是style="font-family:Courier New;"

<div style="font-family:Courier New;">Some text</div>
<div style="font-family:Courier New;">Some text</div>
<div style="font-family:Courier New;">Some text</div>

页面中还有其他 DIV。我只是想针对那些有style="font-family:Courier New;"有什么帮助吗?

您正在寻找querySelectorAll()

var courier = document.querySelectorAll('div[style="font-family:Courier New;"]');
for (var i = 0, len = courier.length; i < len; i++) {
	courier[i].style.color = 'red';
}
<div style="font-family:Courier New;">Some text</div>
<div style="font-family:Courier New;">Some text</div>
<div style="font-family:Arial;">Some text</div>
<div style="font-family:Courier New;">Some text</div>

现在,您可以像在 CSS 中一样编写查询。

适用于所有主流浏览器:http://caniuse.com/#feat=queryselector

你可以

用jQuery来做到这一点:

console.log($("[style='font-family:Courier New;']").length);