http://jsfiddle.net/vol7ron/s5fS8/
-
HTML:
<div class="container"> <span class="foo">a</span> <span class="bar">1a</span> <span class="bar">2a</span> </div> <div class="container"> <span class="foo">b</span> <span class="bar">1b</span> <span class="bar">2b</span> </div> <div class="container"> <span class="foo">c</span> <span class="bar">1c</span> <span class="bar">2c</span> </div> <div class="title">Debug:</div> <pre id="debug"></pre> -
JS:
var debug = $('#debug'); var containers = $('.container'); var foos = containers.children('.foo'); var bars = foos.siblings('.bar:first'); bars.each(function(){ debug.append($(this).text() + '\n'); });
What happens is the first bar is returned, whereas from an OOP POV, you’d think the first bar from each container would be returned.
As I left in a comment, I’m hung on why :first is applied to the result set, rather than the search set.
I thought the logic was: loop through the array of foos, find all the siblings that are bars, but only return the first one, add it to the array result stack, continue on to the next foo.
Instead, it’s: loop through array of foos, find all siblings that are bars, add them to the result stack, select the first one.
I think it should work more like find() where:
containers.find('.bar:first')returns the result I’m looking forcontainers.find('.bar').first(':first')returns the result I’m currently getting (the OOP makes sense)
When you use first you are telling jQuery to get the first it finds from the list you give it not taking into account the parents. To get the result you ask about use this instead:
Demo: http://jsfiddle.net/s5fS8/1/
You can also loop over the containers instead: