2016-02-01 35 views
2

如何使用javascript来计算DIV标签的数量?唯一的属性将永远是style="font-family:Courier New;"计算没有名称或ID的通用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;">Some text</div> 

还有其他的DIV的页面。我只是想瞄准那些有style="font-family:Courier New;" 任何帮助?

+0

'$( '格')长;' – Adam

+0

Ø没有jQuery的:'document.getElementsByTagName( '格')长;' – Adam

+0

这计数的所有div页。我试图只用style =“font-family:Courier New;”来定位 –

回答

4

您正在寻找querySelectorAll()

var courier = document.querySelectorAll('div[style="font-family:Courier New;"]'); 
 

 
for (var i = 0, len = courier.length; i < len; i++) { 
 
\t 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

+1

选择器字符串应该是'div [style =“font - 家庭:快递新;“]'? – guest271314

+0

是的,那会更好,更新。 – chrona

+1

您可以在'='之前添加一个'*':'document.querySelectorAll('div [style * =“font-family:Courier New;”]');'这样可以允许像这样的元素:'

Some text
' – Adam

0

您可以用jQuery做到这一点:

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

不能使用jQuery –