Lessons in this course (10)
3. DOM traversal and manipulation
Basic★ Must knowLesson 3 of 10
js
// Traversal
$(this).parent(); $(this).parents(".card"); $(this).closest("tr");
$(this).children(); $(this).siblings(); $(this).next(); $(this).prev();
// Content
$("#title").text("New title"); // safe text
$("#box").html("<b>Bold</b>"); // parses HTML — never with untrusted input (XSS)
$("#name").val(); // get form value
$("#name").val("Divakar"); // set
// Attributes and properties
$("img").attr("alt", "Logo");
$("#agree").prop("checked", true); // use .prop for checked/disabled/selected (live state)
$("#box").data("id"); // reads data-id (cached by jQuery)
// Classes and CSS
$("#box").addClass("active").removeClass("hidden").toggleClass("open");
$("#box").css({ color: "red", "font-weight": "bold" });
// Insert / remove
$("#list").append("<li>Last</li>").prepend("<li>First</li>");
$("<li>", { text: "Safe item", class: "item" }).appendTo("#list");
$("#old").remove(); // removes element + its jQuery data/events
$("#list").empty(); // removes children
$("#tmp").detach(); // removes but keeps data/events to re-insertattr vs prop: attr reads/writes the HTML attribute (initial value); prop reads/writes the DOM property (current state). For checked, disabled, selected use prop.