Prithviraj Mitra Prithviraj Mitra - 27 days ago 6
HTML Question

How to get next div data attribute using jquery

I am trying to get the next div's data key. But it's giving me 'undefined'

Here is the html code

<div class="sort-arrows"><span class="fa fa-arrow-up" id="sort-up"></span><span class="fa fa-arrow-down" id="sort-down"></span></div>

<div class="flow-content" data-key="2yqz1jpdxwy2g434zyo8r7k6vml9n50d">
<h3 class="bg-primary">Title</h3>
</div>


Demo -- https://jsfiddle.net/v8wkt0yL/

Any help is highly appreciated.

Answer

When the arrow is clicked, your thing of interest is the arrow's parent's sibling.

$("body").on('click tap', '.sort-arrows .fa-arrow-down', function(e) {
  e.preventDefault();

  var $flow = $(this).parent().siblings("div.flow-content:first");

  // ======================
  // also works but more brittle
  // ======================
  // var $flow = $(this).parent().next();
  // ======================

  console.log($flow.data("key"));
});
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" integrity="sha256-eZrrJcwDc/3uDhsdt61sL2oOBY362qM3lon1gyExkL0=" crossorigin="anonymous" />

<div class="sort-arrows">
  <span class="fa fa-arrow-up" id="sort-up"></span>
  <span class="fa fa-arrow-down" id="sort-down"</span>
</div>

<div class="flow-content" data-key="2yqz1jpdxwy2g434zyo8r7k6vml9n50d">
  <h3 class="bg-primary">Title</h3>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>