Find all elements with a certain attribute value in jquery

Jquery

Jquery Problem Overview


I need to find all elements that has a special attribute value.

Here is the div I need to find (I have many of them..)

<div imageId='imageN'>...

I simply need to loop through the divs which have imageId='imageN'

Jquery Solutions


Solution 1 - Jquery

Although it doesn't precisely answer the question, I landed here when searching for a way to get the collection of elements (potentially different tag names) that simply had a given attribute name (without filtering by attribute value). I found that the following worked well for me:

$("*[attr-name]")

Hope that helps somebody who happens to land on this page looking for the same thing that I was :).

Update: It appears that the asterisk is not required, i.e. based on some basic tests, the following seems to be equivalent to the above (thanks to Matt for pointing this out):

$("[attr-name]")

Solution 2 - Jquery

$('div[imageId="imageN"]').each(function() {
    // `this` is the div
});

To check for the sole existence of the attribute, no matter which value, you could use ths selector instead: $('div[imageId]')

Solution 3 - Jquery

It's not called a tag; what you're looking for is called an html attribute.

$('div[imageId="imageN"]').each(function(i,el){
  $(el).html('changes');
  //do what ever you wish to this object :) 
});

Solution 4 - Jquery

You can use partial value of an attribute to detect a DOM element using (^) sign. For example you have divs like this:

<div id="abc_1"></div>
<div id="abc_2"></div>
<div id="xyz_3"></div>
<div id="xyz_4"></div>...

You can use the code:

var abc = $('div[id^=abc]')

This will return a DOM array of divs which have id starting with abc:

<div id="abc_1"></div>
<div id="abc_2"></div>

Here is the demo: http://jsfiddle.net/mCuWS/

Solution 5 - Jquery

Use string concatenation. Try this:

$('div[imageId="'+imageN +'"]').each(function() {
    $(this);   
});

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPabucView Question on Stackoverflow
Solution 1 - Jquerysammy34View Answer on Stackoverflow
Solution 2 - JqueryThiefMasterView Answer on Stackoverflow
Solution 3 - JqueryValView Answer on Stackoverflow
Solution 4 - JqueryKrunalView Answer on Stackoverflow
Solution 5 - JqueryLostSenSSView Answer on Stackoverflow