简体   繁体   中英

Select element by data defined with jquery

I'm trying to select element by data attribute defined with jquery (it's not visible in DOM), therefore I cannot use $('.foo:data(id)')

example: if user clicks element I add data property to it as following

$(this).data('id', '1');

now I would like to find element which has data-id == 1

how can I select this element by data-id?

You could use the attribute selector [attribute=...] .

In your case, this would be

$('[data-id=1]')

But keep in mind, if you change the data of an element with .data() , the change isn't reflected in the dom attribute, so you can't use this (or additionally change the dom attribute).

The other way would be to select every candidate and then filter for each element, which has a matching data value.

$('.foo').filter(function(){
    return $(this).data('id') == 1;
});

Use filter()

$('.foo').filter(function(){
    return $(this).data('id') === `1`
}).doSomething()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM