0

I tried to increment the value of current 'top' property value within a foreach.

http://jsfiddle.net/fqmnksgL/

var percent = 50;
$('div').forEach(function (obj, i) {
    $(obj).css('top', $(obj).css('top') + percent);
});

Is there anything wrong with my code above?

1
  • 1
    $('div') returns a HTMLCollection which is not exaclty as Array, as you might be thinking. forEach is a Array method Commented Apr 16, 2015 at 6:28

3 Answers 3

2

forEach is part of Array. Use each instead. You can use the function callback to increment the top property of the current element.

var percent = 50;
$('div').each(function() {
    $(this).css('top', function(_, top){ 
        return parseInt(top, 10) + percent;
    });
});

But it doesn't work as you intended. Perhaps you should try something like the other answer, which uses $.fn.prev

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

3 Comments

Your answer was way better than mine, but I have two questions. 1) Can't top be undefined? and 2) what is the significance of (+top)?
+ converts string to int.
I tested ur code with the fiddle, it doesn't work jsfiddle.net/fqmnksgL/5
0

You can try

var percent = 50;
$('div').css('top', function(i, obj) {
  return i * percent;
});
div {
  width: 50px;
  height: 50px;
  background: red;
  position: absolute;
  top: 10px;
  left: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>

Comments

0

You can't add percent (%) to px value, you need to convert one of them

var px = 50;
$('div').each(function () {

    $(this).css('top', parseInt($(this).prev().css('top')) + px);
});

http://jsfiddle.net/fqmnksgL/6/

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.