Hi I was just wondering if building an array in javascript was possible using a function like so. I have a variable that is getting the margins of a series of elements using $(ele).css('margin');
. This returns a string of 0px 0px 0px 0px
where I only want the left property to check whether it's been animated -=
left.
I can do a similar function but I know there must be a better way. Here's my example:
var marginsLeft = new array();
$(ele).each(function(i){
var r = $(i).css('margin').split(" ");
marginsLeft[i]=r[3];
});
I'm not entirely sure how to simplify this, but I'm sure it's possible :) thanks in advance.
Hi I was just wondering if building an array in javascript was possible using a function like so. I have a variable that is getting the margins of a series of elements using $(ele).css('margin');
. This returns a string of 0px 0px 0px 0px
where I only want the left property to check whether it's been animated -=
left.
I can do a similar function but I know there must be a better way. Here's my example:
var marginsLeft = new array();
$(ele).each(function(i){
var r = $(i).css('margin').split(" ");
marginsLeft[i]=r[3];
});
I'm not entirely sure how to simplify this, but I'm sure it's possible :) thanks in advance.
Share Improve this question edited Dec 22, 2012 at 11:55 Irvin Dominin 31k9 gold badges80 silver badges113 bronze badges asked Dec 22, 2012 at 11:51 bashleighbashleigh 9,3445 gold badges32 silver badges50 bronze badges 2-
Have you tried it? It should work, yes. However, just getting
css("margin-left")
might be easier… – Bergi Commented Dec 22, 2012 at 11:54 -
$(i)
won't work, since the first parameter or$.each
is the index in the element set. To get the element, either usethis
or the second parameter. – mgibsonbr Commented Dec 22, 2012 at 11:58
3 Answers
Reset to default 6You can use $.map
:
var marginsLeft = $(ele).map(function() {
return parseInt($(this).css('margin-left'), 10);
}).get();
Update: as pointed out by @undefined, if you want a regular array you should also call .get
on the result. Otherwise, you'll have a jQuery wrapped array. It is array-like, so it can be used as an array in many contexts, but not in others (in particular, it may not have the native Array
methods).
Also, to convert the result to a number you can use parseInt
(which will ignore the letters and use only the digits), remembering to explicitate the base (10).
Have a look at the docs for .each()
: The first parameter of the callback function is the index, the array element (DOM node) can be accessed either as the second parameter or the this
value. So, use
var marginsLeft = []; // literal shortcut for "new Array()"
$(ele).each(function(i, el){
marginsLeft[i] = $(el).css('margin-left');
});
You also might have a look at the .map()
method, but that returns a jQuery wrapper object instead of an array.
you could use css('margin-left')
instead