jQuery - Get Content and Attributes


jQuery has powerful methods for manipulating HTML elements and attributes.


jQuery DOM Manipulation

A very important part of jQuery is its ability to manipulate the DOM.

jQuery provides a series of DOM-related methods that make it easy to access and manipulate elements and attributes.

lamp DOM = Document Object Model

DOM defines the standard for accessing HTML and XML documents:

"The W3C Document Object Model is a platform- and language-neutral interface that allows programs and scripts to dynamically access and update the content, structure, and style of documents."



Get content - text(), html(), and val()

Three simple, practical jQuery methods for DOM manipulation:

  • text()- Set or return the text content of the selected elements
  • html()- Set or return the content of the selected elements (including HTML tags)
  • val()- Set or return the value of form fields

The following example demonstrates how to get content using the jQuery text() and html() methods:

Example

$("#btn1").click(function(){ alert("Text: " + $("#test").text()); }); $("#btn2").click(function(){ alert("HTML: " + $("#test").html()); });

Try it Yourself »

The following example demonstrates how to get the value of an input field using the jQuery val() method:

Example

$("#btn1").click(function(){ alert("Value:" + $("#test").val()); });

Try it Yourself »


Get attributes - attr()

The jQuery attr() method is used to get attribute values.

The following example demonstrates how to get the value of the href attribute in a link:

Example

$("button").click(function(){ alert($("#example").attr("href")); });

Try it Yourself »

The next chapter will explain how to set (change) content and attribute values.

Other Extensions