jQuery HTML

Learn how to get and set HTML content with jQuery

📝 jQuery HTML Methods

jQuery provides powerful methods to get and set HTML content, text, and values. You can easily change what users see on your webpage.


// Get content
var content = $("#myDiv").html();

// Set content  
$("#myDiv").html("<h2>New Content!</h2>");
                                    

Result:

New Content!

Main HTML Methods

📄

html()

Get or set HTML content

$("p").html("<b>Bold text</b>")
📝

text()

Get or set text content

$("p").text("Plain text only")
💾

val()

Get or set form field values

$("input").val("Default value")
🏷️

attr()

Get or set attributes

$("img").attr("src", "new.jpg")

🔹 html() Method

The html() method gets or sets the HTML content of elements:

// Get HTML content
var content = $("#demo").html();
console.log(content); // Shows current HTML

// Set HTML content (replaces existing)
$("#demo").html("<h3>New Title</h3><p>New paragraph</p>");

// Set content for multiple elements
$(".info").html("<strong>Important:</strong> Updated info");
<div id="demo">
    <h2>Original Title</h2>
    <p>Original content</p>
</div>

After html() method:

New Title

New paragraph

🔹 text() Method

The text() method gets or sets the text content (no HTML tags):

// Get text content (strips HTML tags)
var textOnly = $("#demo").text();

// Set text content (HTML tags will be displayed as text)
$("#demo").text("This <b>won't</b> be bold");

// Safe way to display user input
var userInput = "<script>alert('hack')</script>";
$("#safe").text(userInput); // Shows as text, doesn't execute
<p id="demo"><b>Bold text</b> and normal text</p>

text() vs html():

text(): Bold text and normal text

html(): Bold text and normal text

🔹 val() Method

The val() method gets or sets the value of form elements:

// Get form values
var name = $("#name").val();
var email = $("#email").val();
var message = $("#message").val();

// Set form values
$("#name").val("John Doe");
$("#email").val("[email protected]");
$("#country").val("USA"); // For select dropdown

// Clear all form fields
$("input, textarea").val("");
<form>
    <input type="text" id="name" placeholder="Your name">
    <input type="email" id="email" placeholder="Your email">
    <select id="country">
        <option value="USA">United States</option>
        <option value="UK">United Kingdom</option>
    </select>
    <textarea id="message" placeholder="Your message"></textarea>
</form>

🔹 attr() Method

The attr() method gets or sets HTML attributes:

// Get attribute value
var imageSrc = $("img").attr("src");
var linkHref = $("a").attr("href");

// Set single attribute
$("img").attr("src", "new-image.jpg");
$("a").attr("href", "https://example.com");

// Set multiple attributes
$("img").attr({
    "src": "photo.jpg",
    "alt": "Beautiful photo",
    "title": "Click to enlarge"
});

// Remove attribute
$("img").removeAttr("title");
<img src="old.jpg" alt="Old image">
<a href="#">Click here</a>

After attr() changes:

🔹 Adding Content

jQuery provides methods to add content without replacing existing content:

// Add content inside elements
$("#container").append("<p>Added at the end</p>");
$("#container").prepend("<p>Added at the beginning</p>");

// Add content outside elements  
$("#container").after("<p>Added after container</p>");
$("#container").before("<p>Added before container</p>");

// Add multiple elements
$("ul").append("<li>Item 1</li><li>Item 2</li><li>Item 3</li>");
<div id="container">
    <p>Original content</p>
</div>

After adding content:

Added before container

Added at the beginning

Original content

Added at the end

Added after container

🔹 Removing Content

Remove elements and content from the page:

// Remove elements completely
$(".unwanted").remove();

// Remove content but keep the element
$("#container").empty();

// Remove specific elements
$("p:contains('delete')").remove();

// Remove elements with specific attributes
$("img[src='old.jpg']").remove();
<div id="container">
    <p>Keep this</p>
    <p class="unwanted">Remove this</p>
    <p>Please delete this paragraph</p>
</div>

🔹 Practical Examples

Real-world usage of jQuery HTML methods:

🔸 Dynamic Content Loading

// Load content based on user selection
$("#category").change(function() {
    var category = $(this).val();
    $("#content").html("<p>Loading " + category + " content...</p>");
    
    // Simulate loading content
    setTimeout(function() {
        $("#content").html("<h3>" + category + "</h3><p>Content loaded!</p>");
    }, 1000);
});

🔸 Form Validation Messages

// Show validation messages
function validateForm() {
    var email = $("#email").val();
    
    if (email === "") {
        $("#email-error").html("<span style='color:red'>Email is required</span>");
        return false;
    } else if (!email.includes("@")) {
        $("#email-error").html("<span style='color:red'>Invalid email format</span>");
        return false;
    } else {
        $("#email-error").html("<span style='color:green'>✓ Valid email</span>");
        return true;
    }
}

🔸 Shopping Cart

// Add item to cart
function addToCart(itemName, price) {
    var cartItem = "<div class='cart-item'>" +
                   "<span>" + itemName + "</span>" +
                   "<span>$" + price + "</span>" +
                   "<button onclick='removeItem(this)'>Remove</button>" +
                   "</div>";
    
    $("#cart").append(cartItem);
    updateTotal();
}

🧠 Test Your Knowledge

Which method should you use to safely display user input?