jQuery Selectors ও DOM Manipulation

লেসন ৩৬ / ৪৪

jQuery Selectors

CSS selector-ই jQuery-তে কাজ করে।

$("*")              // সব element
$("p")              // সব <p>
$("#myId")          // ID
$(".myClass")       // class
$("ul li")          // descendant
$("ul > li")        // direct child
$("h1 + p")         // next sibling
$("input[type='text']")  // attribute

// Pseudo
$("li:first")
$("li:last")
$("li:even")
$("li:odd")
$("li:eq(2)")      // index 2
$("li:gt(2)")       // index > 2
$("li:not(.active)")
$(":input")         // input, select, textarea, button
$(":checked")       // checked checkbox/radio
$(":visible")
$(":hidden")

Content পরিবর্তন

// Text
$("#title").text();                // get
$("#title").text("নতুন টেক্সট");   // set

// HTML
$("#div").html();
$("#div").html("<strong>মোটা</strong>");

// Form value
$("#input").val();
$("#input").val("নতুন মান");

// Attribute
$("img").attr("src");
$("img").attr("src", "new.jpg");
$("img").attr({ src: "new.jpg", alt: "..." });
$("input").removeAttr("disabled");

// Data attribute
$("#el").data("id");          // data-id পড়া
$("#el").data("id", 42);      // set

// Property (checked, disabled)
$("input").prop("checked", true);
$("button").prop("disabled", true);

CSS ও Class

// Inline CSS
$(".box").css("color", "red");
$(".box").css({
    color: "red",
    background: "yellow",
    fontSize: "20px"
});
let color = $(".box").css("color");  // get

// Class manipulation ⭐
$(".box").addClass("active");
$(".box").removeClass("hidden");
$(".box").toggleClass("open");
$(".box").hasClass("active");       // true/false

// Dimensions
$(".box").width();           // content width
$(".box").innerWidth();      // + padding
$(".box").outerWidth();      // + padding + border
$(".box").outerWidth(true);  // + margin
$(".box").height();
$(".box").offset();          // {top, left} viewport
$(".box").position();        // parent এর relative

Element যোগ/মুছে ফেলা

// ভিতরে (শেষে)
$("ul").append("<li>নতুন</li>");
$("<li>নতুন</li>").appendTo("ul");

// ভিতরে (শুরুতে)
$("ul").prepend("<li>প্রথমে</li>");

// বাইরে (আগে)
$("ul").before("<h2>শিরোনাম</h2>");

// বাইরে (পরে)
$("ul").after("<p>নিচে</p>");

// মুছে ফেলা
$(".box").remove();           // পুরো সরায়
$(".box").empty();            // শুধু ভিতর খালি
$(".box").detach();           // সরায় কিন্তু data রাখে

// Replace
$(".old").replaceWith("<div class='new'>...</div>");

// Clone
$(".box").clone().appendTo("body");

Traversing

$("li").first();
$("li").last();
$("li").eq(2);             // ৩য়টি

$("li").parent();
$("li").parents(".wrap");  // সব ancestor
$("li").closest(".wrap");  // নিকটতম

$("ul").children();
$("ul").find("a");          // descendant

$("li.active").next();
$("li.active").prev();
$("li.active").siblings();

// Filter
$("li").filter(".important");
$("li").not(".disabled");
$("li").has("a");          // যেগুলোর ভিতরে <a> আছে