jQuery text()
with callback function
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script>/*from www .j a va2s. c om*/ <script> $(document).ready(function(){ $("button").click(function(){ $("p").text(function(n){ return "This p element has index: " + n; }); }); }); </script> </head> <body> <button>Set text content of the p elements</button> <p>This is a paragraph.</p> <p>This is another paragraph.</p> </body> </html>