1

I have a jQuery object which I get via code such as this:

var elements = $('#all_cats_holder div.wSelect-option-selected').detach();

The code it gets will be something such as:

<div class="wSelect-option wSelect-option-selected"><div class="wSelect-option-value" data-val="2">Some stupid cat #2</div></div>
<div class="wSelect-option wSelect-option-selected"><div class="wSelect-option-value" data-val="3">Some stupid cat #3</div></div>
<div class="wSelect-option wSelect-option-selected"><div class="wSelect-option-value" data-val="4">Some stupid cat #4</div></div>

Now I'm trying to loop through this data and get the value of data-val but I can't seem to get it to work.

My code:

var mr_val;

$.each(elements, function(index, el) {

    mr_val = el.data('val');

    alert(mr_val);            

});

I don't even get an alert at all.

5
  • That's because you're looping through the outer divs, which have no data-val attribute. You want to traverse to the child div, and then pull the attribute from that. Commented Apr 4, 2014 at 16:56
  • Those elements doesn't seem to match the class given in the selector, are you sure that's what you're getting. Commented Apr 4, 2014 at 16:57
  • @PatrickQ Ahh... that's probably it. Thanks. Commented Apr 4, 2014 at 17:00
  • @adeneo My bad. Updated. Commented Apr 4, 2014 at 17:00
  • Note that el inside the loop is not a jQuery object, and has no data() method Commented Apr 4, 2014 at 17:01

1 Answer 1

2

Why not just make it an array with $.map

var mr_val = $.map(elements, function(el) {
    return $(el).find('[data-val]').data('val');
});

FIDDLE

or with each

var mr_val;

$.each(elements, function(index, el) {

    mr_val = $(el).find('div').data('val');

    alert(mr_val);            

});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.