简体   繁体   中英

How to reach specific elements by attribute value in Javascript

Lets say i have this HTML code:

<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.

I did manage to do it using for loop and checking the value on each element, but is there a shorter way?

你可以试试

document.querySelectorAll("a[rel=cookie]");

If you don't mind using a JavaScript library, you can use jQuery

 var cookies = $('a[rel="cookie"]')

more info on jQuery selectors: http://api.jquery.com/category/selectors/

This has the added benefit of working with older browsers.

For modern browsers use querySelectorAll

like

var els;
if(document.querySelectorAll){
    els = document.querySelectorAll('a[rel="cake"]')
} else {
    //use a loop
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM