Clean β’ Professional
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.
// Get HTML content
let content = $("#demo").html();
// Set HTML content
$("#demo").html("<b>Hello, World!</b>");
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!");
Used for form elements such as input, textarea, and select.
// Get value
let name = $("#username").val();
// Set value
$("#username").val("John Doe");
Adds new content inside the selected element, after existing content.
$("p").append(" This is appended text.");
Adds new content inside, but before existing content.
$("p").prepend("Start: ");
Inserts content outside the selected element, after it.
$("p").after("<hr>");
Inserts content outside the selected element, before it.
$("p").before("<h4>Introduction:</h4>");
Deletes the selected elements from the document.
$("#demo").remove();
Clears the inner HTML content but keeps the element itself.
$("#container").empty();
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"
});
Removes an attribute from an element.
$("img").removeAttr("alt");
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>Β