'w3schools example regarding jQuery callback function with index

In this example, a jQuery function is presented that when clicked, it prints out the old text and the new text of the element, plus the index of the current element. I'm pretty sure the index must increment (because new elements are being added). But upon testing the code, why is the index showing 0 all the time?

$("#btn1").click(function(){
  $("#test1").text(function(i,origText){
    return "Old text: " + origText + " New text: Hello world!
    (index: " + i + ")"; 
  });
});

$("#btn2").click(function(){
  $("#test2").html(function(i,origText){
    return "Old html: " + origText + " New html: Hello <b>world!</b>
    (index: " + i + ")"; 
  });
});


Solution 1:[1]

Here is the same example re-written to explain index...

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("#btn1").click(function(){
    $(".test1").text(function(i, origText){
      return "Old text: " + origText + " New text: Hello world! (index: " + i + ")"; 
    });
  });

  $("#btn2").click(function(){
    $(".test1").html(function(i, origText){
      return "Old html: " + origText + " New html: Hello <b>world!</b> (index: " + i + ")"; 
    });
  });
});
</script>
</head>
<body>

<p>This is a <b>bold</b> paragraph.</p>

<ul>
<li class="test1" >item number 1</li>
<li class="test1" >item number 2</li>
<li class="test1" >item number 3</li>
</ul>

<p class="test1">This is another <b>bold</b> paragraph.</p>

<button id="btn1">Show Old/New Text</button>
<button id="btn2">Show Old/New HTML</button>

</body>
</html>

I'm studying on W3schools right now and had the same question. Googling led me to this question and the answers are kind of cryptic. after fiddling with the code i found this and thought someone else might need a clearer answer.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mohamed Naji