Login

Username:

Password: 

Join us Now |  Forgot Password? | Forgot UserName?

jQuery

Learn step by step



Getting and setting content [text(), html() and val()]

The simplest aspect of DOM manipulation is retrieving and setting text, values and HTML. These 3 things might seem like the same thing, but they are not. Text is a textual (no HTML) representation of the inner content for all regular elements, values are for the form elements and HTML is the same as text, but it include any markup.

Fortunately for us, jQuery comes with a method for each of the 3, allowing us to both retrieve and set these properties: The text(), html() and val() methods/functions. Here is a little example which will show us the difference between them and how simple they are to use:


<div id="divText"></div>
<div id="divHtml"></div>
<input type="text" id="txtTest" name="txtTest" value="Input field" />

<script type="text/javascript">
$(function()
{
$("#divText").text("A dynamically set text");
$("#divHtml").html("<b><i>A dynamically set HTML string</i></b>");
$("#txtTest").val("A dynamically set value");
});
</script>

And that is how easy it is to set text, values and HTML.

These 3 functions comes with one overload, where you can specify a callback function as the first and the only parameter. This callback method will be called with two parameters by jQuery, index of the current element in the list of elements selected, as well as existing value, before it is replaced with a new value. We then return the string that we wish to use as the new value from function. This overload works for both text(), html() and val(), but for the sake of simplicity, we only use text() version in this example:


<p>Paragraph 1</p>
<p>Paragraph 2</p>
<p>Paragraph 3</p>

<script type="text/javascript">
$(function()
{
$("p").text(function(index, oldText) {
return "Existing text: " + oldText + ". New text: A dynamically set text (#" + index + ")";
});
});
</script>

We start out with 3 similar paragraph elements, which text is the only difference between them. In jQuery code, we select all of them and then use the special version of the text() function to replace their current text with a newly constructed text, based on two parameters that jQuery provides for us: Index of the current element as well as its current text. This new text is then returned to the jQuery, which will replace the current text with the new.



Related Videos