TakN TakN - 1 month ago 5
jQuery Question

The Sibling Function

I would like to know what are the requirements for the sibling() function. For instance which selector will come in the parameters () if the html is as below and I am targeting the now div class and could you explain in a bit of detail which parent element or what is suppose to be in the parameters. Thanks all help is appreciated

$(function(){
$(".target").click(function(){
$(this).siblings(".a_cont").slideDown(100);
});
})

<div class='yes'>
<div class='what'>
<button class='target'> </button>
<div class='now'> </div>
</div>
</div>

<div class='yes'>
<div class='what'>
<button class='target'> </button>
<div class='now'> </div>
</div>
</div>

Answer

The jQuery API documentation is really usually quite helpful. This is the page on .siblings().

The documentation states:

Given a jQuery object that represents a set of DOM elements, the .siblings() method allows us to search through the siblings of these elements in the DOM tree and construct a new jQuery object from the matching elements.

The method optionally accepts a selector expression of the same type that we can pass to the $() function. If the selector is supplied, the elements will be filtered by testing whether they match it.

So you start with a jQuery object, such as $(this) in your example. .siblings() will find all of the sibling elements in the DOM tree, and the result is a new jQuery object. The selector allows you to filter out elements. So to do what you want from the button that has your handler requires the code:

$(this).siblings(".now");

That takes the class now as the filter.

Comments