[英]How to reach specific elements by attribute value in Javascript
Lets say i have this HTML code: 可以说我有这个HTML代码:
<a href="mysite.com" rel="cookie"></a>
<a href="mysite.com" rel="cake"></a>
<a href="mysite.com" rel="cookie"></a>
Is there a quick way to select only the 2 a tags with the cookie rel value. 有没有一种快速的方法来仅选择具有cookie rel值的2 a标签。
I did manage to do it using for loop and checking the value on each element, but is there a shorter way? 我确实使用for循环并检查了每个元素的值来做到这一点,但是有没有更短的方法呢?
你可以试试
document.querySelectorAll("a[rel=cookie]");
If you don't mind using a JavaScript library, you can use jQuery 如果您不介意使用JavaScript库,则可以使用jQuery
var cookies = $('a[rel="cookie"]')
more info on jQuery selectors: http://api.jquery.com/category/selectors/ 有关jQuery选择器的更多信息: http : //api.jquery.com/category/selectors/
This has the added benefit of working with older browsers. 与旧版本的浏览器一起使用具有更多的好处。
For modern browsers use querySelectorAll 对于现代浏览器,请使用querySelectorAll
like 喜欢
var els;
if(document.querySelectorAll){
els = document.querySelectorAll('a[rel="cake"]')
} else {
//use a loop
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.