Suliman Sharif Suliman Sharif - 5 months ago 20
Javascript Question

Grab a position of the Span element

I am trying to generate a sequence of elements that I would like to print out to the user. Each span element has a click a function attached to it, and when clicked, will highlight a different part of the program. So what I want to do is (after the elements are generated) lets say this is what we have

<div id = "sequence label">
<span>K</span>
<span>L</span>
<span>A</span>
<span>S</span>
<span>G</span>
</div>


I was thinking of grabbing the index of the span somehow when clicked and corresponding that with another index in a list so lets say:

data = [2, 3, 4, 5, 6]


so grabbing the first element [0] will give me the data [2].

Answer

You can use jQuery's .index() function

var data = [2, 3, 4, 5, 6];
$("span").click(function() {
  var index = $(this).index();
  console.log(data[index]);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
    <span>K</span>
    <span>L</span>
    <span>A</span>
    <span>S</span>
    <span>G</span>
</div>