简体   繁体   中英

jQuery, search for element with value in attribute among the matched elements

I find a collection of a tags using jQuery like this:

itemsPresent = $('h3.zn-ItemTitle > a');

Later in my scripts I need to find the a within the matched elements with a specific url in its href attribute without making a new jQuery select.

How can I do this?

You can use the attribute equals selector:

itemsPresent = $('h3.zn-ItemTitle > a[href="http://your-url.com"]');

Alternatively, if you want to keep them as separate objects:

var itemsPresent = $('h3.zn-ItemTitle > a'),
    filteredAnchors = itemsPresent.filter('[href="http://your-url.com"]');

Use .filter() to filter the Jquery object based on your desired conditions.

Try,

itemsPresent.filter(function(){   
  return $(this).attr('href') == 'something';
}) 

Or as BenM suggested you can use,

itemsPresent.filter('[href="something"]');

You can filter the collection

itemsPresent = $('h3.zn-ItemTitle > a');

var otherItems1 = itemsPresent.filter('[href="someUrl"]');

//or

var otherItems2 = itemsPresent.filter(function() {
    return this.href.indexOf('someURL') != -1;
});

You can use filter :

var $a = itemsPresent.filter(function() {
    return $(this).prop('href') == 'http://your-website.com';
});

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