jQuery - Set Content and Attributes
Set content - text(), html() and val()
We will use the same three methods from the previous chapter to set content:
- text() - sets or returns the text content of the selected elements
- html() - sets or returns the content of the selected elements (including HTML markup)
- val() - sets or returns the value of a form field
The following example shows how to set content with the text(), html() and val() methods:
Example
$
(
"
#btn1
"
)
.
click
(
function
(
)
{
$
(
"
#test1
"
)
.
text
(
"
Hello world!
"
)
;
}
)
; $
(
"
#btn2
"
)
.
click
(
function
(
)
{
$
(
"
#test2
"
)
.
html
(
"
Hello world!
"
)
;
}
)
; $
(
"
#btn3
"
)
.
click
(
function
(
)
{
$
(
"
#test3
"
)
.
val
(
"
RUNOOB
"
)
;
}
)
;
Try it »
Callback functions for text(), html() and val()
The three jQuery methods above - text(), html() and val() - also have callback functions. The callback has two parameters: the index of the current element in the list of selected elements, and the original (old) value. It then returns the string you want to use as the new value.
The following example shows text() and html() with callback functions:
Example
$
(
"
#btn1
"
)
.
click
(
function
(
)
{
$
(
"
#test1
"
)
.
text
(
function
(
i
,
origText
)
{
return
"
Old text:
"
origText
"
New text: Hello world! (index:
"
i
"
)
"
;
}
)
;
}
)
; $
(
"
#btn2
"
)
.
click
(
function
(
)
{
$
(
"
#test2
"
)
.
html
(
function
(
i
,
origText
)
{
return
"
Old html:
"
origText
"
New html: Hello world! (index:
"
i
"
)
"
;
}
)
;
}
)
;
Try it »
Set attributes - attr()
The jQuery attr() method is also used to set/change attribute values.
The following example shows how to change (set) the value of the href attribute in a link:
Example
$
(
"
button
"
)
.
click
(
function
(
)
{
$
(
"
#runoob
"
)
.
attr
(
"
href
"
,
"
http://www.runoob.com/jquery
"
)
;
}
)
;
Try it »
The attr() method also lets you set multiple attributes at once.
The following example shows how to set both href and title attributes:
Example
$
(
"
button
"
)
.
click
(
function
(
)
{
$
(
"
#runoob
"
)
.
attr
(
{
"
href
"
:
"
http://www.runoob.com/jquery
"
,
"
title
"
:
"
jQuery tutorial
"
}
)
;
}
)
;
Try it »
Callback function for attr()
The jQuery method attr() also provides a callback function. The callback has two parameters: the index of the current element in the list of selected elements, and the original (old) value. It then returns the string you want to use as the new value.
The following example shows the attr() method with a callback function:
Example
$
(
"
button
"
)
.
click
(
function
(
)
{
$
(
"
#runoob
"
)
.
attr
(
"
href
"
,
function
(
i
,
origValue
)
{
return
origValue
"
/jquery
"
;
}
)
;
}
)
;
Try it »