简体   繁体   中英

finding a particular data-id in a parent container using jquery

Say if I have the following html:

<a href="some url" class="product-store-name">
    azzaharastore
</a>

and this html is contained inside another div, and another div, of x levels. Is there a way to find the div that has the data-id in it and then get the value of it? In other words I want a function that propates upwards and find the data-id in it.

You can use .closest() along with has attribute selector to find the desired element

if this refers to this element then use(replace this with any other means to refer the target element)

var $div = $(this).closest('div[data-id]'); 
var did = $div.data('id');

or for the above said case

var did  = $('.product-store-name').closest('div[data-id]').data('id')

Demo: Fiddle

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