jQuery DOM Manipulation – Easy Access and Control
One of the core strengths of jQuery is its ability to manipulate the DOM
(Document Object Model) with ease.
jQuery offers a wide range of built-in methods that allow you to quickly
access, modify, and interact with HTML elements and their attributes.
Whether you're changing content, updating styles, or handling structure,
jQuery makes DOM manipulation simple and efficient.
Getting Content with jQuery – text(), html(), and val()
jQuery provides a few simple yet powerful methods to retrieve or update
content in your web pages. Among them, three commonly used methods
are:
- text() – Gets or sets the text content of selected elements (without HTML tags).
- html() – Gets or sets the HTML content, including any tags, within the selected elements.
- val() – Gets or sets the value of form elements like input fields, textareas, or dropdowns.
Example – Getting Text and HTML Content
$("#btn1").click(function() {
alert("Text: " + $("#test").text());
});
$("#btn2").click(function() {
alert("HTML: " + $("#test").html());
});
In this example:
Clicking Button 1 displays the plain text inside the #test element.
Clicking Button 2 displays the HTML content inside #test, including any
tags.
Getting Input Field Values with jQuery – val()
The jQuery val() method is used to get or set the value of form
elements, such as input fields, textareas, and select dropdowns.
Example – Retrieving the Value of an Input Field
$("#btn1").click(function() {
alert("Value: " + $("#test").val());
});
In this example, when the button is clicked, an alert will display the
current value entered in the input field with the ID #test.
This method is especially useful for working with user input in
forms.
Getting Attribute Values with jQuery – attr()
The jQuery attr() method allows you to retrieve the value of an HTML
attribute from a selected element.
Example – Getting the href Attribute from a Link
$("button").click(function() {
alert($("#w3s").attr("href"));
});
In this example, when the button is clicked, it displays the value of
the href attribute from the element with the ID #w3s—typically a
hyperlink.
This method is useful when you need to access dynamic attributes like
src, href, alt, or title.
More topic in jQuery