Select data value from grandparent div?

I have the element below. I want to use the ‘Quick View’ button to display a modal which will have content from the REST API. The data-post-id= value is what contains the value I need to get via javascript to send to the API call.

How do I use javascript to select the value from a grandparent element?

<div class="jet-listing-grid__item jet-listing-dynamic-post-2" data-post-id="2">
   <div class="is-vertical is-layout-flex wp-container-9389-4 wp-block-group cr-card-to-list">
      <div class="is-vertical is-layout-flex wp-container-9389-1 wp-block-group"><div class="" data-is- 
     block="jet-engine/dynamic-image"><div class="jet-listing jet-listing-dynamic-image"><a 
      href="https://dev.coosrealty.com/properties/412233-denture-st/" class="jet-listing-dynamic-image__link"><img width="300" height="150" src="https://dev.coosrealty.com/wp-content/uploads/revslider/pano2-300x150.jpg" class="jet-listing-dynamic-image__img attachment-medium size-medium" alt="" decoding="async" loading="lazy" srcset="https://dev.coosrealty.com/wp-content/uploads/revslider/pano2-300x150.jpg 300w, https://dev.coosrealty.com/wp-content/uploads/revslider/pano2-1024x512.jpg 1024w, https://dev.coosrealty.com/wp-content/uploads/revslider/pano2-768x384.jpg 768w, https://dev.coosrealty.com/wp-content/uploads/revslider/pano2-1536x768.jpg 1536w, https://dev.coosrealty.com/wp-content/uploads/revslider/pano2-2048x1024.jpg 2048w" sizes="(max-width: 300px) 100vw, 300px"></a></div></div></div>



<div class="is-vertical is-layout-flex wp-container-9389-3 wp-block-group">
<h6>1234 Somewhere Blvd, Coos Bay </h6>

<button> Quick View </button> 
</div>
</div>
</div>
</div>

From the button on click:

this.parentElement.parentElement.parentElement.getAttribute('data-post-id')

You can also use closest. Just use the closest to get the element, and if you want to get the value, then use the dataset.postId

btn.closest("[data-post-id]").dataset.postId
4 Likes

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.