In Action

Modify HTML Text using JQuery

It is possible to append or modify html text using jquery. At first blush this might not seem all that practical to do, this technique can be used to communicate to the end user instead of using the alert boxes which can get annoying. This technique can also be combined with ajax in order to update a page when data changes server side.

This is text in a paragraph tag.



Personally, I do not see a great deal of value in modifying static text up in the browser. However, I am presenting these techniques now as one never knows when they will they will run into a scenario when this might need to be done.


Note: These buttons are not part of a form. This code (as written) will not work if you make it part of a form.



JQuery Code

JQuery Code for our example

     $("#replace").click(function(){
	   	 $("#ptag").html(" Replacing original text with this text");
	   	 var ihtml = $("#ptag").text();
	   	 //alert(ihtml);
     });
 
     $("#append").click(function(){
	   	 $("#ptag").append(" appending this text.");
	   	 var ihtml = $("#ptag").text();
	   	 //alert(ihtml);
     });
      
     
    $("#reset").click(function () {
	      location.reload();
    });

HTML Code

HTML Code for our example

	<p id="ptag">This is text in a paragraph tag.</p>
	<br />
    <button id="replace">Replace</button>
    <button id="append">Append</button> 
    <button id="reset">Reset</button>