0

JS Code

<script type="text/javascript">
    var list = document.getElementsByClassName('sortByTestName');

    for (var i = 0; i < list.length; i++) {
        var current = list[i].innerHTML;
        list[i].onclick = function() {
            window.alert(current);
        }

    }
</script>

Ok so the code here iterates through html file finding elements by class name and i made a for loop that goes through that. All the elements are displayed on the screen and when one element is clicked i would like to alert the value of the element that was clicked. For example lets say elements are numbers 1-10. They are displayed vertically in page and when user clicks on say number 3 browser should alert in box 3. Everything in terms of design/display is working. The problem I have is that when ever I click on any element the last element is always showing. In terms of our number example if user clicks on number 5 last number 10 is showing. If user clicks on any number last number is showing. I believe this is because the whole loop is executing before something is clicked. I am wondering how I can fix this.

0

1 Answer 1

1

var list = document.getElementsByClassName('sortByTestName');

for (var i = 0; i < list.length; i++) {
  list[i].onclick = function() {
    window.alert(this.innerHTML);
  }
}
div:hover {
  cursor: pointer;
}
<div class="sortByTestName">
  <span>Here is some inner html</span>
</div>
<div class="sortByTestName">
  <span>Some more inner html</span>
</div>

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

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.