jQuery Set

In jQuery, the set methods allow you to dynamically update the content and attributes of elements. These methods enable interactive and customizable web applications by modifying the properties of HTML elements on the fly.

Key Topics

Setting Text Content

Use the text() method to update the text content of an element.

$("#element").text("Updated Text Content");

Explanation: This code updates the text content of the element with the ID element to "Updated Text Content".

Setting HTML Content

Use the html() method to update the HTML content of an element, including its child elements and tags.

$("#element").html("Updated HTML Content");

Explanation: This code updates the HTML content of the element with the ID element, replacing its current content with the specified HTML.

Setting Input Values

Use the val() method to set a new value for an input field.

$("#inputField").val("New Input Value");

Explanation: This code sets the value of the input field with the ID inputField to "New Input Value".

Setting Attributes

Use the attr() method to set a new value for an attribute of an element.

$("#link").attr("href", "https://newurl.com");

Explanation: This code updates the href attribute of the link element with the ID link to point to "https://newurl.com".

Example: Set Methods


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>jQuery Set Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
    <p id="textElement">Original Text</p>
    <input id="inputField" type="text" value="Original Value">
    <a id="link" href="https://example.com">Visit Example</a>
    <button id="setButton">Set New Values</button>

    <script>
        $(document).ready(function() {
            $("#setButton").click(function() {
                $("#textElement").text("Updated Text");
                $("#inputField").val("Updated Value");
                $("#link").attr("href", "https://updated.com");
            });
        });
    </script>
</body>
</html>
                    

Explanation: This example demonstrates how to update text, input values, and attributes dynamically using the set methods in jQuery.

Key Takeaways

  • Dynamic Updates: Use text(), html(), val(), and attr() to modify element content and attributes in real-time.
  • Flexibility: The set methods provide an easy way to update both plain text and HTML.
  • Attribute Control: Use attr() to dynamically change attributes like href, src, and others.