Filter element based on .data() key/value

前端 未结 5 1469
庸人自扰
庸人自扰 2020-12-12 13:08

Say I have 4 div elements with class .navlink, which, when clicked, use .data() to set a key called \'selected\', to a value of

5条回答
  •  北海茫月
    2020-12-12 14:10

    Just for the record, you can filter on data with jquery (this question is quite old, and jQuery evolved since then, so it's right to write this solution as well):

    $('.navlink[data-selected="true"]');
    

    or, better (for performance):

    $('.navlink').filter('[data-selected="true"]');
    

    or, if you want to get all the elements with data-selected set:

    $('[data-selected]')
    

    Note that this method will only work with data that was set via html-attributes. If you set or change data with the .data() call, this method will no longer work.

提交回复
热议问题