user254799
user254799

Reputation: 75

Get each element's attribute through $.each()

Trying to do $('div').attr('data', 'ip') through a .each() just returns undefined.

Let's say I have 4 divs

    <div class="box" data-ip="ipvalue">content</div>
    <div class="box" data-ip="ipvalue">content</div>
    <div class="box" data-ip="ipvalue">content</div>
    <div class="box" data-ip="ipvalue">content</div>

and I need to iterate each one and get the data-ip value.

My code, it just returns undefined (server, serverObj, are variables).

var serversObj = $('.server');
serversObj.each(function(index, el) {
    return $(this).data('ip');
});

What am I doing wrong?

Upvotes: 1

Views: 46

Answers (4)

PeterKA
PeterKA

Reputation: 24638

Here is what the code should be for the markup sample you gave.

var serversObj = $('.box'),
Ipvals = [];
serversObj.each(function(index, el) {
    Ipvals.push( $(this).data('ip'));
});
console.log( Ipvals);

You can also use $.map() to return the same array.

Upvotes: 0

epascarello
epascarello

Reputation: 207511

You want to use map if you want to get all of the values of all of the elements

var ips = $(".box")  //get all of the elements
              .map( 
                  function(){ 
                      return $(this).data("ip"); //get the value from the attribute
                  }
              ).get();  //returns an Array 

Fiddle

Upvotes: 2

user229044
user229044

Reputation: 239311

First off, this is totally wrong:

$('div').attr('data', 'ip')

This is setting an attribute called data to a value of "ip", it does nothing involving data attributes. Effectively, you're doing this: <div data='ip'>.

If you want to access a data attribute called data-ip, you want

$('div').data('ip')

If you want to access it for a series of elements, you can't just return it out of a .each loop. That value is discarded. You need to map your input set of elements to a set of outputs:

$('.server').map(function () { return $(this).data('ip') })

This will produce an array that has each element matched by .server's data-ip attribute.

Upvotes: 0

jhyap
jhyap

Reputation: 3837

$('.box').each(function(){
    console.log($(this).attr('data-ip'));

});

Upvotes: 0

Related Questions