Find all elements with a certain attribute value in jquery
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..)
开发者_Go百科<div imageId='imageN'>...
I simply need to loop through the divs which have imageId='imageN'
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]")
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]")
$('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]')
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 :)
});
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);
});
精彩评论