jQuery HTML Methods
jQuery provides several methods to get, set, add, and remove HTML content and attributes.
These make it easy to update a webpage dynamically without writing complex JavaScript.
html() – Get or Set HTML Content
- Get: Returns the HTML content of the first matched element.
- Set: Replaces the HTML content of all matched elements.
// Get HTML content
let content = $("#demo").html();
// Set HTML content
$("#demo").html("<b>Hello, World!</b>");
text() – Get or Set Text Content
Used to get or change only the text (without HTML tags).
// Get text
let txt = $("p").text();
// Set text
$("p").text("This is new text!");
val() – Get or Set Form Input Value
Used for form elements such as input, textarea, and select.
// Get value
let name = $("#username").val();
// Set value
$("#username").val("John Doe");
append() – Insert Content at the End
Adds new content inside the selected element, after existing content.
$("p").append(" This is appended text.");
prepend() – Insert Content at the Beginning
Adds new content inside, but before existing content.
$("p").prepend("Start: ");
after() – Insert Content After an Element
Inserts content outside the selected element, after it.
$("p").after("<hr>");
before() – Insert Content Before an Element
Inserts content outside the selected element, before it.
$("p").before("<h4>Introduction:</h4>");
remove() – Remove Elements
Deletes the selected elements from the document.
$("#demo").remove();
empty() – Remove Inner Content
Clears the inner HTML content but keeps the element itself.
$("#container").empty();
attr() – Get or Set Attributes
Used to get or change HTML attributes (like src
, href
, alt
, etc.)
// Get attribute
let link = $("a").attr("href");
// Set single attribute
$("a").attr("href", "<https://example.com>");
// Set multiple attributes
$("img").attr({
"src": "photo.jpg",
"alt": "Nature Image"
});
removeAttr() – Remove Attribute
Removes an attribute from an element.
$("img").removeAttr("alt");
prop() – Get or Set Properties
Used for DOM properties (like checked
, selected
, disabled
, etc.)
$("#check1").prop("checked", true);
Example: HTML Methods
<!DOCTYPE html>
<html>
<head>
<title>jQuery HTML Methods Example</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
<h2 id="title">Welcome</h2>
<p id="text">This is a paragraph.</p>
<input type="text" id="username" value="Guest">
<button id="btn">Update</button>
<script>
$(document).ready(function() {
$("#btn").click(function() {
$("#title").html("<b>Hello, User!</b>");
$("#text").append(" (Updated using jQuery)");
$("#username").val("John Doe");
});
});
</script>
</body>
</html>