4

html

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

jquery

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

I would like to know origText is not called outside function but it is returning the value. How?

demo

Bhojendra Rauniyar
  • 83,432
  • 35
  • 168
  • 231

4 Answers4

2

As docs says

function(index, text)

A function returning the text content to set. Receives the index position of the element in the set and the old text value as arguments.

And How does jQuery’s .text() work, internally?

Community
  • 1
  • 1
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
2

The actual method text takes a function as a parameter. The function passed to text may contain two parameters, the first of which receives the index, the second the original text.

Plymouth223
  • 1,905
  • 1
  • 12
  • 22
0

Function text does some preparations about input nodes and then runs callback provided by user (your function), and it pass to your callback this two arguments (which prepared on "some preparations") step. If you want exact code, you can read jQuery source.

Tommi
  • 3,199
  • 1
  • 24
  • 38
0

In simple:

text(function(whatever){
      return whatever; // returns the text what is the text it has.
    });

In your example p has text : This is a bold paragraph.

return whatever will return your text : This is a bold paragraph.

Navin Rauniyar
  • 10,127
  • 14
  • 45
  • 68