jQuery Get Content and Attributes
- Previous Page jQuery Chaining
- Next Page jQuery Setting
jQuery has powerful methods for manipulating HTML elements and attributes.
jQuery DOM Operations
A very important part of jQuery is its ability to operate DOM.
jQuery provides a series of methods related to DOM, which makes it easy to access and manipulate elements and attributes.
Tip:DOM = Document Object Model (Document Object Model)
DOM defines the standard for accessing HTML and XML documents:
"The W3C Document Object Model is an interface independent of platform and language, allowing programs and scripts to dynamically access and update the content, structure, and style of documents."
Get Content - text(), html() and val()
Three simple and practical jQuery methods for DOM operations:
- text() - Set or return the text content of the selected element
- html() - Set or return the content of the selected element (including HTML tags)
- val() - Set or return the value of a form field
The following example demonstrates how to obtain content using the jQuery text() and html() methods:
Example
$("#btn1").click(function(){ alert("Text: " + $("#test").text()); }); $("#btn2").click(function(){ alert("HTML: " + $("#test").html()); });
The following example demonstrates how to obtain the value of an input field using the jQuery val() method:
Example
$("#btn1").click(function(){ alert("Value: " + $("#test").val()); });
Get Attribute - attr()
The jQuery attr() method is used to get the attribute value.
The following example demonstrates how to obtain the value of the href attribute in a link:
Example
$("button").click(function(){ alert($("#w3s").attr("href")); });
The next chapter will explain how to set (change) content and attribute values.
jQuery HTML Reference Manual
For a complete list of jQuery HTML methods, please visit the following reference manual:
- Previous Page jQuery Chaining
- Next Page jQuery Setting