jQuery - Get Content and Attributes


JQuery contains powerful ways to modify and manipulate HTML elements and attributes.


jQuery DOM Manipulation

The most important part of jQuery is that it is possible to use DOM.

JQuery comes with a number of DOM-related features that make it easy to access and trick elements and attributes.


DOM = Document Object Model

DOM defines the level of access to HTML and XML documents:

"The W3C Document Object Model (DOM) is a platform with a virtual interface that allows programs and documents to dynamically access and update content, structure, and style of text."



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

Three simple, but useful, jQuery methods for DOM manipulation are:

  • text() - Sets or returns the text content of selected elements
  • html() - Sets or returns the content of selected elements (including HTML markup)
  • val() - Sets or returns the value of form fields

The following example illustrates how to find content with jQuery text() and html() methods:


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

The following example illustrates how to get the input field value via jQuery val():


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


Get Attributes - attr()

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

The following example shows how you get the href attribute value in a link:


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

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