DOM manipulation with jQuery allows you to modify, add, remove, or interact with data on a web page by targeting the DOM structure. jQuery provides convenient methods and functions to perform DOM manipulation tasks.
Here are explanations for each section along with specific examples:
Selecting elements
$("p")
: Select all<p>
elements on the page.$(".myClass")
: Select all elements with the classmyClass
.$("#myElement")
: Select the element with the IDmyElement
.$("parentElement").find(".childElement")
: Select all child elements with the classchildElement
within theparentElement
.
Example:
$("p").css("color", "red");
Changing content
$("#myElement").html("<b>Hello World</b>")
: Set the HTML content for the element with the IDmyElement
.$("p").text("New text")
: Set the text content for all<p>
elements.
Example:
$("p").text("New paragraph");
Adding and removing elements
$("ul").append("<li>New item</li>")
: Add an<li>
element at the end of the unordered list (<ul>
).$(".myClass").remove()
: Remove all elements with the classmyClass
from the page.
Example:
$("ul").append("<li>Item 4</li>");
Changing attributes and classes
$("img").attr("src", "new-image.jpg")
: Change thesrc
attribute value for all<img>
elements.$("#myElement").addClass("newClass")
: Add the classnewClass
to the element with the IDmyElement
.$("#myElement").removeClass("oldClass")
: Remove the classoldClass
from the element with the IDmyElement
.
Example:
$("img").attr("alt", "New Image");
Event handling
$("button").click(function() { })
: Register an event handler function when a <button>
element is clicked.
Example:
$("button").click(function() {
alert("Button clicked!");
});
Effects and animations
$("#myElement").hide()
: Hide the element with the IDmyElement
.$("#myElement").show()
: Show the element with the IDmyElement
.$("#myElement").fadeOut()
: Perform a fade-out effect on the element with the IDmyElement
.$("#myElement").fadeIn()
: Perform a fade-in effect on the element with the IDmyElement
.
Example:
$("#myElement").fadeOut(1000, function() {
console.log("Fade out complete");
});