Frequently we may have to add or update content of the HTML elements in the web pages. The data we need to add or edit may come from various sources dynamically. jQuery has number of utility methods to achieve this goal. We can add elements or edit element’s data using jQuery. For instance, we can update the contents of the DIV tag using jQuery’s text(),html() or load() methods.
text() Method
The jQuery’s text() method is used to get the text contents of the selected element. The element to get the text content can be selected using the selector syntax. The following snippet of code gets the contents of the DIV tag.
also read:
If you are looking for a good book on jQuery, please buy jQuery in Action
Here is the DIV tag.
<div id="myDiv"> <p>This is the content of the DIV tag myDiv</p> </div>
The jQuery code to get the DIV tag’s content.
$("#myDiv").text()
We can also use text() method to set the contents of any element. In this case, we need to provide the new content as an argument to the text() method. The following snippet of code updates the DIV myDiv with new text.
$("#myDiv").text('<b>myDiv After Update</b>');
Optionally, we can also have a function which can return the new content being set and also have access to index and old content being replaced. The following is the example of the text() method with function usage.
$("#myDiv").text(function(index, currentContent) { alert(index + ' ' + currentContent); return "myDiv After Update"; });
The parameters index specifies the index position of the element and currentContent specifies the current content of the element. The current content will be replaced with new content.
When used text() method to return the contents of an element, the HTML markup in the content will be removed and text part only will be returned.
html() Method
The jQuery’s html() method gets the HTML contents of the selected element. The element to get the HTML content can be selected using standard selector syntax. The following code snippet updates the DIV myDiv’s HTML content with new HTML tags.
$("#myDiv").html('<h1>myDiv After Update</h1>');
Just like text() method with function we can also have html() method with function as shown in the below example:
$("#myDiv").html(function(index, currentContent) { alert(index + ' ' + currentContent); return "myDiv After Update"; });
When used html() method to return the contents of an element, the HTML markup in the content will be returned.
load() Method
We can also use load() method to update the selected element’s content. This is particularly useful if the content to be updated is residing externally and accessible via URL. The example code retrieves content from externally located welcome.htm and updates the DIV myDiv.
$("#myDiv").load('welcome.html');
These are the possible ways jQuery can refresh the element content.
also read:
If you are looking for a good book on jQuery, please buy jQuery in Action