3

I am trying to first get the value of the order property of an element, and then adding 1 to it when I click a button. Thing is, instead of getting 1 and adding 1 and getting 2, I get 11. Shouldn't the "+=" operator add the values? What am I doing wrong?

carouselPrev.addEventListener("click", function(){

  const firstPost = document.querySelector(".blog-post");

  let firstPostOrder = firstPost.style.getPropertyValue('order');

  firstPost.style.order = firstPostOrder += 1;
});
1
  • 3
    You need to treat firstPostOrder as an integer using parseInt() before doing arithmetic. Otherwise, you're just appending 1 to a string. Commented Aug 23, 2018 at 13:22

4 Answers 4

7

Css properties are strings, and '1' + 1 = 11.

Add "+" before firstPostOrder to convert it to a number.

firstPost.style.order = +firstPostOrder += 1;

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

1 Comment

That did work thank you. Accepting when it allows me to.
2

the values are strings so they are be concatenated, try parsing to an integer before using parseInt()

Comments

1

Try this

carouselPrev.addEventListener("click", function(){

const firstPost = document.querySelector(".blog-post");

let firstPostOrder = firstPost.style.getPropertyValue('order');

firstPost.style.order = parseInt(firstPostOrder,10) +1;
});

2 Comments

Always suggest radix with parseInt i.e. parseInt(firstPostOrder, 10) see stackoverflow.com/questions/6611824/why-do-we-need-to-use-radix
That is just not working. The order is not changing at all.
1

No, the "+=" operator is an assignment operator you'd use in lieu of "=".

let x = 42;
x += 1;

is equivalent to

let x = 42;
x = x + 1;

You want to use just the "+" to add the values, not the "+=".

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.