So i'm working on a script, and I'm in a situation where i'm dealing with a set of elements on a webpage which all have a similar Class Name which goes like this:

<span class="values">1 </span>
<span class="values">2 </span>
<span class="values">23 </span>

The value of the third one changes all the time and I would like to define that third one in the list specifically. How do I define the "23" knowing it can always change in value? What I tried doing is getting it this way, but it doesn't work:

var numbers = document.getElementsByClassName("values"),
    rank = numbers[3];

So what i'm doing here is:

  • I first get all elements with classname "values".
  • Then I define the third element in the list of elements

What am I doing wrong here? Maybe even though in the "inspect element" menu they appear underneath each other, there is no such ranking, so it doesn't know what i mean with [3]?

.

Thanks for helping!

PS: I know that third value is always bigger than 20.

有帮助吗?

解决方案

the array starts with [0], so what you want is element[2] you may also want to add "innerHTML" to just get the value.

var numbers = document.getElementsByClassName("values"),
    rank = numbers[2].innerHTML;

http://jsfiddle.net/tBA73/

其他提示

If you want to get the rank of the third element as a number, you should do the following:

var numbers = document.getElementsByClassName("values"),
    rank = parseInt(numbers[2].innerHTML, 10);
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top