steve Kim steve Kim - 3 months ago 16
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
in between the
classes and store them in an object. It will be 2,3,4,5 in this case.

var number_store = [];

How would I achieve this?



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)

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');

<script src=""></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: