Joni
Joni

Reputation: 95

getting data from elements stored in an object

Right so I'm trying to work out a way I can check the elements in the object for a particular piece of data, and then filter them out if necessary.

I've got a simple list, I'm running through all the list items and putting them in an object. Later on I want to run through and check each element for a data id.

<ul id="test">
    <li data-id="1">a</li>
    <li>b</li>
    <li>c</li>
    <li>d</li>
    <li>e</li>
    <li>f</li>
    <li>g</li>
    <li>h</li>
    <li data-id="2">i</li>
    <li>j</li>
    <li>k</li>
    <li>l</li>
    <li>m</li>
    <li>n</li>
</ul>`


var holder = {};
i = 0;
$('#test li').each(function(){
    holder[i]=$(this);
    i++
});
$('#test').append(holder[2]);
holder.each(function(){
    console.log($(this).attr('data-id'));

});

I'm sure one of you clever people out there will be able to tell me how to get this going in no time. It's probably painstakingly obvious!

Cheers for the help guys.

Upvotes: 1

Views: 119

Answers (2)

Ram
Ram

Reputation: 144669

There is no need to create an extra object, by selecting elements using jQuery selectors you have an object.

var $holder = $('#test li');

$holder.each(function(){
     console.log($(this).data('id'));
     // console.log(this.dataset.id);
})

if you want to select the li elements that have data-id attributes you can use attribute selector:

var $holder = $('#test li[data-id]');

And for storing values you can use map method:

var data = $('#test li[data-id]').map(function(){
                return this.dataset.id;
           }).get() // [1, 2]

Upvotes: 4

Viktor S.
Viktor S.

Reputation: 12815

You have a simple array with a list of items in it, not jQuery object here:

holder.each(function(){
    console.log($(this).attr('data-id'));

});

if you want to loop through items of such array you should use:

$.each(holder, function(){
    console.log($(this).attr('data-id'));

});​

But from your code you do not need that. You may do something like below:

$('#test li').each(function(){
    console.log($(this).attr('data-id'));
});
$('#test').append($('#test li').eq(2));

Upvotes: 0

Related Questions