JQuery: find siblings of the same element type

Given an unordered nested list, if you find the first occurrence of "li", how do you find all siblings that are at the same level?

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

Update: my question was not formulated correctly. I really need to know the following. If I have a link to an element, how can I find the siblings elements and create a set that will include the element itself and siblings of the same element type, in this case "li"?

+4
source share
2 answers

If you want to include the source element, you will need

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

Edit: jQuery is deprecated by itself. This is still the main answer, so for future use addBack may be what you want

 $(this).siblings("li").addBack(); 
+9
source

If you are dealing with a list, you only need to look at the brothers and sisters. The list itself contains only li elements and nothing else, so it will be enough:

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

If you are not sure about the name of the node, you can remove it from the first element:

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

If you need to follow this logic over and over, it might be wise to provide you with a method by extending jQuery.fn:

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

Allows you to call a new method, like any other filtering method:

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

So, in this case, any type of the first child is the types of siblings that we will retrieve. If this is a paragraph, we will get all the paragraphs. If this is an image, we will get all the images. Please note, however, that this is based only on the tag and not on the class (although that would be just as easy to accomplish).

+4
source

All Articles