jQuery Get Content and Attributes
jQuery has simple methods to read the content, the form values and the attributes of elements.
The page for the examples
<div id="box">
<p class="note">Hello <b>world</b></p>
<p class="note">Second paragraph</p>
<a id="link" href="https://example.com/page" title="Example page" data-id="42" data-role="admin">Link</a>
<input type="text" id="name" value="Anita">
<input type="checkbox" id="agree" checked>
</div>
text(), html() and val()
| Method | Returns |
|---|---|
.text() | The text of the elements (HTML tags removed). For many elements, the text of all of them joined |
.html() | The HTML inside the first element |
.val() | The value of a form field |
console.log($('.note').first().text());
console.log($('.note').text());
console.log($('.note').first().html());
console.log($('#name').val());
Hello world
Hello worldSecond paragraph
Hello <b>world</b>
Anita
Notice: .text() on two paragraphs joins both texts, and .html() reads only the first element.
attr(): read an attribute
console.log($('#link').attr('href'));
console.log($('#link').attr('title'));
console.log($('#link').attr('target'));
https://example.com/page
Example page
undefined
If the attribute does not exist, .attr() returns undefined.
prop(): read a property
For checkboxes, radio buttons and options, use .prop(). It gives the real current state, as true or false.
console.log($('#agree').prop('checked'));
console.log($('#agree').is(':checked'));
console.log($('#agree').attr('checked'));
true
true
checked
attr() vs prop()
| attr() | prop() |
|---|---|
| Reads the value written in the HTML | Reads the current value of the DOM property |
| Result is a string (or undefined) | Result has the right type: true or false, number |
| Use for href, src, title, id, data attributes | Use for checked, selected, disabled, value |
data(): read data attributes
HTML5 data-* attributes can be read with .data(). It converts numbers and booleans for you.
console.log($('#link').data('id'));
console.log(typeof $('#link').data('id'));
console.log($('#link').data('role'));
console.log($('#link').data());
42
number
admin
{ id: 42, role: 'admin' }
Get the HTML of the element itself
console.log($('#link')[0].outerHTML);
<a id="link" href="https://example.com/page" title="Example page" data-id="42" data-role="admin">Link</a>
jQuery has no method for the outer HTML, so we take the DOM element with [0] (or .get(0)) and use the plain JavaScript property.
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |