oboer oboer - 1 year ago 78
jQuery Question

jQuery basics (theory) - what can I do with index (i) parameter in .text(i, x), .html(i, x) or .val(i, x)?

I'm going through jQuery tutorial on ws3school. I understand how it works, but I cannot think in what way it can be used.

Example from website below or here.

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

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

<!DOCTYPE html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

<p id="test1">This is a <b>bold</b> paragraph.</p>
<p id="test2">This is another <b>bold</b> paragraph.</p>

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


Anyone could give an example? Code appreciated, but not necessary.

Answer Source

You may need to use it in a case like this:

$( "ul li" ).text(function( index ) {
  return "item number " + ( index + 1 );

Which means .text(index) might be useful when you use it in arrays.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download