How to get elements by a specific value of a custom attribute in jQuery?

后端 未结 4 1334
天命终不由人
天命终不由人 2021-01-19 16:28

I have a custom attribute called data-role and I\'d like to find all elements where data-role=\"content\" in jQuery.

相关标签:
4条回答
  • 2021-01-19 17:02

    jQuery select by attribute selector:

    $('[data-role="content"]')
    

    And for an array use .each(); instead of for

    $('[data-role="content"]').each(function(){
      alert($(this).html());
    });
    
    0 讨论(0)
  • 2021-01-19 17:03

    Check out jQuery's list of attribute selectors. You're looking for something like

    $('div[data-role="content"]')
    
    0 讨论(0)
  • 2021-01-19 17:04

    use attribute equals selector

    $("div[data-role='content']")
    

    u can find more info here

    0 讨论(0)
  • 2021-01-19 17:06
    $("tagName[attribute='value']")
    

    Or, in your case:

    $("div[data-role='content']")
    

    Will return the right elements.

    From there, if you wanted to iterate over the set of elements that match this selector and do something evil, you could:

    $("[data-role='content']").each(function(index){
    
         Do something evil
         $(this) is the current element in the iteration
    });
    

    Please note that the tagName is optional. JQuery selectors can be concatenated at will, so you can query simulataneously for tagname (simple string), id (prefaced by #), class (prefaced by .) or attribute (in square brackets as above), or for any limited combination of them eg:

     $("tagName#someId.someClass.someOtherClass[attribute='value']")
     $("[attribute='value']")
     $('tagName')
     $('#someId')
    

    Are all valid queries, however keep in mind that jquery will only return elements that match ALL conditions in the query.

    0 讨论(0)
提交回复
热议问题