0

I have this strange problem I can't get my head around. I try to find the highest number in a list of elements which have a data-index attribute for their respective number. But when iterating over them, JS insists that 9 < 10 is false.
See this fiddle: http://jsfiddle.net/1ztbxbjx/

What I'm doing wrong?

I can't use

for (i = 0; i < $('div[data-index]'; i++))

Sometimes there will be numbers out of order in the list (eg. 1,2,3,4,5,25,31).

2
  • 3
    looks like you are doing a string comparison Commented Jun 29, 2015 at 15:07
  • 1
    those indexes are returning strings. they are not true numbers you will need to convert the string to a number. Commented Jun 29, 2015 at 15:07

3 Answers 3

2

You need to parse the id, otherwise you're comparing strings. Here is an example using parseInt()

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

1 Comment

couldn't remember the function off top my head so didn't want to do an answer. kudos to you
1

Parse retreived id to Number and it should work fine, try this:

var current = Number($(this).attr('id')); 

Tested in JSFiddle, its working fine after this one line change.

Cheers !

Comments

1

Use this

if (indexCount < parseInt(current)) {

instead of

if (indexCount < current) {

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.