jQuery Set Content and Attributes
The same methods that read content can also change it. You only pass a value as the argument.
<div id="box">
<p id="p1">Old text</p>
<p id="p2">Old html</p>
<input type="text" id="name" value="">
<a id="link" href="#">Link</a>
<input type="checkbox" id="agree">
<button id="send">Send</button>
</div>
Set text, html and value
$('#p1').text('New text');
$('#p2').html('New <b>bold</b> html');
$('#name').val('Ravi');
<div id="box">
<p id="p1">New text</p>
<p id="p2">New <b>bold</b> html</p>
<input type="text" id="name" value="">
<a id="link" href="#">Link</a>
<input type="checkbox" id="agree">
<button id="send">Send</button>
</div>
.text() treats the value as plain text, so special characters like < are escaped. .html() reads the value as HTML. Do not use .html() with text from the users, because it can create a security problem (XSS).
Safe vs unsafe
<div id="out"></div>
var userInput = '<img src=x onerror=alert(1)>';
$('#out').text(userInput); // safe: shown as text
console.log($('#out').html());
<img src=x onerror=alert(1)>
Set attributes
$('#link').attr('href', 'https://example.com');
$('#link').attr({
title: 'Example site',
target: '_blank',
'data-id': 7
});
<a id="link" href="https://example.com" title="Example site" target="_blank" data-id="7">Link</a>
Use an object to set many attributes at one time.
Set properties
$('#agree').prop('checked', true);
$('#send').prop('disabled', true);
console.log('checked property: ' + $('#agree').prop('checked'));
checked property: true
<div id="box">
<p id="p1">Old text</p>
<p id="p2">Old html</p>
<input type="text" id="name" value="">
<a id="link" href="#">Link</a>
<input type="checkbox" id="agree">
<button id="send" disabled="">Send</button>
</div>
Notice that the property checked is true now, but there is no checked attribute written in the HTML below. The attribute is the starting value from the HTML, and the property is the live state.
Remove an attribute
$('#link').attr('title', 'Hello');
$('#link').removeAttr('title');
console.log($('#link').attr('title'));
undefined
Use a function to set the value
The value can be a function. It gets the index of the element and the old value, and returns the new value. It is useful when each element needs a different value.
<ul>
<li>Apple</li>
<li>Banana</li>
<li>Mango</li>
</ul>
$('li').text(function (index, oldText) {
return (index + 1) + '. ' + oldText;
});
<ul>
<li>1. Apple</li>
<li>2. Banana</li>
<li>3. Mango</li>
</ul>
Set a data value
<div id="card"></div>
$('#card').data('count', 5);
console.log($('#card').data('count'));
console.log($('#card').attr('data-count'));
5
undefined
The method .data() stores the value in memory, and does not change the HTML attribute. If you need the attribute in the HTML, use .attr('data-count', 5).
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |