Spectator6
Spectator6

Reputation: 403

jQuery How to filter an object array based on the value of a data-attribute?

If I'm dealing with a returned array of images, how do I filter out only those images that contain a particular data-attribute value?

For example...

let $exampleImages = $("#example img");

Now each of the example images returns something like

$exampleImages[5] => <img ... data-targetattribute="12345" ... >

How could I filter out only those images that contain the data-targetattribute="12345"?

I was thinking the following would work, but it doesn't...

$exampleImages.filter('[data-targetattribute="12345"]');

Any ideas? Is there something to the filter method or in regard to the object collection that I'm not understanding properly?

I'm not married to jQuery either so if this is something that'd be better suited to a raw Javascript approach, I'm all ears!

Thank you!

Upvotes: 1

Views: 136

Answers (1)

Dehodson
Dehodson

Reputation: 459

To filter items with a given data attribute value from a jQuery object, the .filter([selector]) method will achieve what you want.

Here is a bit of example code demonstrating this:

var divs = $('div');

divs = divs.filter('[data-targetattribute="12345"]')

divs.css('background-color', 'red');

JSFiddle

Be mindful that .filter returns a new object. The issue that you're having with your code may be that you are trying to reference the initial variable, which has not been changed.

Upvotes: 2

Related Questions