在 jquery 中查找具有某个属性值的所有元素

我需要找到所有具有特殊属性值的元素。

这是我需要找到的 div (我有很多这样的 div... ...)

<div imageId='imageN'>...

我只需要循环通过有 imageId='imageN'的 div

164300 次浏览

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 :)
});
$('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]')

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]")

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/

Use string concatenation. Try this:

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