Manu Padmanabhan
Manu Padmanabhan

Reputation: 555

how to get all next <tr> data-id on click a <tr>(selected tr)

I want the data-id of all next tr of selected tr in an array. I use this code but this is not a good one.

var ids = Array.prototype.slice.call($("tr.selected").nextAll('tr')); 
alert(ids)
.map(function (tr) { 
    return tr.getAttribute('data-id') 
});

Upvotes: 2

Views: 1135

Answers (2)

Pranav C Balan
Pranav C Balan

Reputation: 115222

Use jQuery map() and get() methods

// iterate over elements using map and generate array elelements
var res = $("tr.selected").nextAll('tr').map(function(){
   // get data attribute value
   return $(this).data('id');
   // get the result object as an array using get method
}).get();

If you want to get all siblings attribute value then use siblings() method instead.

var res = $("tr.selected")
   // get all sibling tr     
   .siblings()
   // iterate over elements using map and generate array elelements
   .map(function(){
   // get data attribute value
   return $(this).data('id');
   // get the result object as an array using get method
}).get();

Upvotes: 1

VisioN
VisioN

Reputation: 145398

In fact the code may look like that:

var ids = $('tr.selected').nextUntil('.selected').map(function() {
  return $(this).data('id');
}).get();

So as a demo, consider the following example:

$('tr.selected').each(function() {
  var ids = $(this).nextUntil('.selected').map(function() {
    return $(this).data('id');
  }).get();

  console.log( ids );
});
.selected {
  background: #ccc;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table border="1">
  <tr data-id="1"><td>Row 1</td></tr>
  <tr data-id="2" class="selected"><td>Row 2</td></tr>
  <tr data-id="3"><td>Row 3</td></tr>
  <tr data-id="4"><td>Row 4</td></tr>
  <tr data-id="5" class="selected"><td>Row 5</td></tr>
  <tr data-id="6"><td>Row 6</td></tr>
  <tr data-id="7"><td>Row 7</td></tr>
</table>

Upvotes: 1

Related Questions