jQuerybeginner 7 min
Read and change text, HTML, attributes and classes, and add or remove elements.
How to change text, attributes and CSS classes, and how to add or remove elements.
A page that never changes is just a document. Updating content after something happens is what makes it feel alive.
The DOM (Document Object Model) is the browser's live version of your HTML. jQuery methods let you read and change it.
Common methods:
.text("hi"): set plain text. .text() reads it..html("<b>hi</b>"): set HTML..attr("src", "pic.png"): set an attribute..addClass("on"), .removeClass("on"), .toggleClass("on").append(x), .prepend(x): add inside an element..remove(): delete it.Most setter methods return the selection, so you can chain them: $("p").addClass("big").text("Hi").
$("#msg").text(...) replaces the text, and .addClass("big") (chained) applies the style.append adds a new list item at the end, prepend at the start.Add a third item, and remove the first one with $("#list li").first().remove().
.html() with user input, which can open the door to script injection. Prefer .text()..text(...) replaces everything inside the element..attr() and .prop() for form state. Use .prop("checked") for checkboxes..text(), .html(), .attr() read and change content and attributes..addClass(), .removeClass() and .toggleClass() manage styling..append(), .prepend(), .remove() change the tree; chain methods for short code.Next: reacting to clicks and other events.
<style>
.big { font-size: 28px; color: royalblue; }
</style>
<p id="msg">Original text</p>
<ul id="list"><li>One</li></ul>
<script>
$(function () {
$("#msg").text("Changed by jQuery").addClass("big");
$("#list").append("<li>Two</li>");
$("#list").prepend("<li>Zero</li>");
});
</script>