steve Kim steve Kim - 2 months ago 9
jQuery Question

jQuery storing attribute into an array or object between two classes

I have following markup.

<div class="block" my_id="1">1</div>
<div class="block first" my_id="2">2</div>
<div class="block" my_id="3">3</div>
<div class="block" my_id="4">4</div>
<div class="block last" my_id="5">5</div>
<div class="block" my_id="6">6</div>


I want to select the values for
my_id
in between the
first
and
last
classes and store them in an object. It will be 2,3,4,5 in this case.

var number_store = [];
$('.first').nextUntil('last').attr('my_id')//??


How would I achieve this?

Thanks!

Answer

my_id is not a valid HTML attribute. You should use data-* attributes to store custom values.

Use jQuery's .andSelf() method to include both, .first and .last elements.


EDIT (thanks for comment)

.andSelf()
This function has been deprecated and is now an alias for .addBack(), which should be used with jQuery 1.8 and later.

var number_store = $('.first').nextUntil('.last').addBack().next().addBack().map(function(){
  return $(this).attr('data-id');
}).get();

console.log(number_store);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="block" data-id="1">1</div>
<div class="block first" data-id="2">2</div>
<div class="block" data-id="3">3</div>
<div class="block" data-id="4">4</div>
<div class="block last" data-id="5">5</div>
<div class="block" data-id="6">6</div>

number_store will hold an array.


Other references: