epitka
epitka

Reputation: 17637

jQuery: find siblings of the same element type

Given an unorder nested list, if one finds a first occurrence of the "li", how does one find all the siblings that are on the same level?

root.find('li:first')...?

Update: My question was not formulated correctly. I actually need to know following. If I have a reference to element, how do I find elements siblings and create a set that will include element itself and the siblings of the same element type, in this case 'li'?

Upvotes: 4

Views: 8023

Answers (2)

Blair Mitchelmore
Blair Mitchelmore

Reputation: 301

If you want to include the original element as well, you'll need

$(this).siblings("li").andSelf();

Edit: jQuery has deprecated andSelf. This is still the top answer, so for future use addBack might be what you want

$(this).siblings("li").addBack();

Upvotes: 9

Sampson
Sampson

Reputation: 268344

If you're dealing with a list, you need only look at the siblings. The list itself with only have li elements, and nothing else, so the following will be sufficient:

$(this).siblings().andSelf();

If you're not sure of the nodeName, you could lift that from the first element:

var elem = $("#container :first-child");
elem.siblings( elem.prop("nodeName") ).andSelf();

If you find yourself needing to perform this logic over and over, it might be wise to provide a method for yourself by extending jQuery.fn:

jQuery.extend( jQuery.fn, {
    typeSiblings: function(){
        return this.siblings( this.prop("nodeName") );
    }
});

Which permits you to call the new method like any other filter method:

$("#container :first-child").typeSiblings().andSelf();

So in this case, whatever type of the first child is, that is the types of siblings we will retrieve. If it's a paragraph, we'll get all paragraphs. If it's an image, we'll get all images. Note however that this is based on the tagname alone, and not the class (though that would be just as easy to accomplish).

Upvotes: 4

Related Questions