Getting and setting content [text(), html() and val()]
The simplest aspect of DOM manipulation is retrieving and setting text, values and HTML. These three things might seem like the same thing, but they're not. Text is a textual (no HTML) representation of the inner content for all regular elements, values are for form elements and HTML is the same as text, but including any markup.
Fortunately for us, jQuery comes with a method for each of the three, allowing us to both retrieve and set these properties: The text(), html() and val() methods. Here's a little example which will show you the difference between them and how simple they are to use:
So a call to one of these methods with no parameters will simply return the desired property. If we want to set the property instead, we simply specify an extra parameter. Here's a complete example:
And that's how easy it is to set text, HTML and values.
These three functions comes with one overload more though, where you specify a callback function as the first and only parameter. This callback function will be called with two parameters by jQuery, the index of the current element in the list of elements selected, as well as the existing value, before it's replaced with a new value. You then return the string that you wish to use as the new value from the function. This overload works for both html(), text() and val(), but for the sake of simplicity, we only use the text() version in this example:
We start out with three similar paragraph elements, which text is their only difference. In the jQuery code, we select all of them and then use the special version of the text() method to replace their current text with a newly constructed text, based on the two parameters that jQuery provides for us: The index of the current element as well as its current text. This new text is then returned to jQuery, which will replace the current text with the new one.