jQuery Get

jQuery Get Content and Attributes

One of the most important parts of jQuery is manipulating the Document Object Model (DOM).

jQuery makes it incredibly easy to access and read content from your HTML elements.

Search engines value clean DOM manipulation, making jQuery a great choice for dynamic content.


Getting Content: text(), html(), and val()

jQuery contains three powerful methods for DOM manipulation.

The text() method sets or returns the text content of selected elements.

The html() method sets or returns the content of selected elements, including HTML markup.

The val() method sets or returns the value of form fields (like input boxes).


The text() Method Example

The text() method strips out any HTML tags and returns only the plain text.

Get Text Content:

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

The html() Method Example

Unlike text(), the html() method returns the text along with its formatting tags.

Get HTML Content:

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

The val() Method Example

When dealing with user input in forms, you use the val() method.

It accurately grabs whatever the user has typed into an input field.

Get Form Value:

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

Getting Attributes: attr()

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

For example, you can get the href attribute from a link (<a> tag).

Get Attribute:

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

Exercise 1 of 1

?

Which jQuery method is used to get the text of an element WITHOUT the HTML formatting tags?