Advertisement

Google Ad Slot: content-top

jQuery Get


jQuery provides a powerful set of methods to dynamically change and manipulate HTML content, elements, and attributes and making it super easy to build interactive web pages.


jQuery DOM Manipulation


DOM manipulation lets you interact with and dynamically change HTML content, structure, and styles without reloading the page.

With just a few lines of jQuery, you can:

  • Change the content of elements
  • Add or remove elements
  • Modify attributes or CSS styles
  • Respond to user actions like clicks, input, or keypresses

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

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

Method

Description

Example

.text()

Get the text content (plain text)

$("#p1").text()

.html()

Get the HTML content (including tags)

$("#p1").html()

.val()

Get the value of form elements

$("#input1").val()

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

Example
<script>
let text = $("#p1").text(); // Hello World
let html = $("#p1").html(); // Hello <b>World</b>
</script>
Try it yourself

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

Example
<script>
$(document).ready(function(){
$("button").click(function(){
alert("Value: " + $("#test").val());
});
});
</script>
Try it yourself

Get Attributes - attr()


Use .attr("attributeName") to get the value of any attribute.


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

Example
<script>
$(document).ready(function(){
$("button").click(function(){
alert($("#link").attr("href"));
});
});
</script>
Try it yourself