I have structures that look like this :
<div class="wanted" id="but-not-really">
<div class="wanted">
<div class="dad">
<input class="reference"/>
<input class="wanted"/>
<input class="bro3"/>
</div>
</div>
</div>
And I want to get the width of either an ancestor (div.wanted
) or a sibling (input.wanted
) of my .reference
element (which is $(this)
in my JS loop), depending of which is the closest.
If I only wanted to seek through the ancestors, I would use $(this).closest('.wanted').width()
.
If I only wanted to seek through the siblings, I would use $(this).siblings('.wanted').width()
.
I tried to use $(this).parents().find('.wanted').width()
but the webpage contains other elements up the document that are interfering. That's why I'm looking for the closest .wanted
element among the siblings and the ancestors.
SOLUTION N°1 (thanks to @undefined) :
At first check the siblings using
siblings
method, if the collection is empty then useclosest
.
var width = $(this).siblings('.wanted').length === 0
? $(this).closest('.wanted').css('width')
: $(this).siblings('.wanted').css('width');