jQuery examples summary 2
Blogs20112011-08-07
Continue the jQuery examples summary, start from my favorite closest().
//1. closest()
$(document).bind("click", function (e) {
$(e.target).closest("li").toggleClass("hilight");
});
//2. children( [ selector ] )
Get the children of each element in the set of matched elements,
optionally filtered by a selector.
//3. find( selector )
$('li.item-ii').find('li').css('background-color', 'red');
$('li.item-ii').find('li') is equivalent to $('li', 'li.item-ii').
var newText = $("p").text().split(" ").join("</span> <span>");
newText = "<span>" + newText + "</span>";
$("p").html(newText).find('span').hover(
function() { $(this).addClass("hilite"); },
function() { $(this).removeClass("hilite");
}).end()
.find(":contains('t')")
.css({"font-style":"italic","font-weight":"bolder"});
//4. next( [ selector ] )
$("button[disabled]").next().text("this button is disabled");
$("p").next(".selected").css("background", "yellow");
if($(this).parent().next().length == 0) {
$('#news ul li:first-child').addClass('active');
} else {
$(this).parent().next().addClass('active');
}
$("a.description").click(function(){
$(this).nextAll(“p.hidden:first”).slideToggle();
});
//5. nextAll( [ selector ] )
Get all following siblings of each element in the set of
matched elements,optionally filtered by a selector.
//6. parent( [ selector ] )
$('li.item-a').parent().css('background-color', 'red');
$("*", document.body).each(function () {
var parentTag = $(this).parent().get(0).tagName;
$(this).prepend(document.createTextNode(parentTag + " > "));
});
//7. parents( [ selector ] )
$('li.item-a').parents().css('background-color', 'red');
var parentEls = $("b").parents().map(function () {
return this.tagName;
}).get().join(", ");
$("b").append("<strong>" + parentEls + "</strong>");
//8. prev( [ selector ] )
$('li.third-item').prev().css('background-color', 'red');
var $curr = $("#start");
$curr.css("background", "#f99");
$("button").click(function () {
$curr = $curr.prev();
$("div").css("background", "");
$curr.css("background", "#f99");
});
$("p").prev(".selected").css("background", "yellow");
//9. siblings( [ selector ] )
$('li.third-item').siblings().css('background-color', 'red');
var len = $(".hilite").siblings()
.css("color", "red")
.length;
$("b").text(len);
var myItems = $('x').find('Item label').filter(function() {
return $(this).text() == 'some string';
}).siblings('web_url');
//10. prevUntil( [ selector ] )
Get all preceding siblings of each element up to but not
including the element matched by the selector.
$('#term-2').prevUntil('dt').css('background-color', 'red');What is the difference between filter(), find() and siblings()?
- filter: take current set and reduce it, eg table rows, filter : odd, odd rows only
- find: descendants of set, eg cells of table rows
- siblings: elements at the same level, eg siblings of a table row = the other rows in the table
