Find all elements with a certain attribute value in jquery

后端 未结 5 1026
旧时难觅i
旧时难觅i 2020-12-02 11:16

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..)

相关标签:
5条回答
  • 2020-12-02 11:35

    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 :) 
    });
    
    0 讨论(0)
  • 2020-12-02 11:35

    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/

    0 讨论(0)
  • 2020-12-02 11:39
    $('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]')

    0 讨论(0)
  • 2020-12-02 11:39

    Use string concatenation. Try this:

    $('div[imageId="'+imageN +'"]').each(function() {
        $(this);   
    });
    
    0 讨论(0)
  • 2020-12-02 11:43

    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]")
    
    0 讨论(0)
提交回复
热议问题