DOM Manipulation with jQuery -Techniques and Examples

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 class myClass.
  • $("#myElement"): Select the element with the ID myElement.
  • $("parentElement").find(".childElement"): Select all child elements with the class childElement within the parentElement.

Example:

$("p").css("color", "red");

 

Changing content

  • $("#myElement").html("<b>Hello World</b>"): Set the HTML content for the element with the ID myElement.
  • $("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 class myClass from the page.

Example:

$("ul").append("<li>Item 4</li>");

 

Changing attributes and classes

  • $("img").attr("src", "new-image.jpg"): Change the src attribute value for all <img> elements.
  • $("#myElement").addClass("newClass"): Add the class newClass to the element with the ID myElement.
  • $("#myElement").removeClass("oldClass"): Remove the class oldClass from the element with the ID myElement.

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 ID myElement.
  • $("#myElement").show(): Show the element with the ID myElement.
  • $("#myElement").fadeOut(): Perform a fade-out effect on the element with the ID myElement.
  • $("#myElement").fadeIn(): Perform a fade-in effect on the element with the ID myElement.

Example:

$("#myElement").fadeOut(1000, function() {
  console.log("Fade out complete");
});