Given a containing jQuery object $c that has multiple elements in it that contain elements with classnames tmpSelected and selected, I would like to select only one element from $c for each classname, preferably tmpSelected. The markup is a complex version of this:
<ul id="a">
<li class="selected"><a href="foo">Foo</a></li>
<li><a href="bar">Bar</a></li>
<li><a href="baz">Baz</a></li>
<li><a href="biz">Biz</a></li>
</ul>
<ul id="b">
<li><a href="woo">Woo</a></li>
<li><a href="war">War</a></li>
<li class="tmpSelected"><a href="waz">Waz</a></li>
<li><a href="wiz">Wiz</a></li>
</ul>
<ul id="c">
<li class="selected"><a href="xuu">Xuu</a></li>
<li class="tmpSelected"><a href="xur">Xur</a></li>
<li><a href="xuz">Xuz</a></li>
<li><a href="xyz">Xyz</a></li>
</ul>
In this case what I want to end up with is $("#a > .selected, #b > .tmpSelected, #c > .tmpSelected") – I want to avoid the .selected element if it has a sibling of .tmpSelected, and I don’t want to select more than one child element for each member of $c where $c = $("#a, #b, #c").
So this is what I came up with:
var $c = $("#a, #b, #c");
var $selected = $c.map(function (idx, el) {
var $el = $(el);
var $tmpSel = $el.children(".tmpSelected");
return $tmpSel.length ? $tmpSel : $el.children(".selected");
});
Is there a reasonable way to do this without explicit looping? (P.S. – It’s fine to return an empty selector when no .tmpSelected or .selected child exists.)
Here is a selector but it is pretty messy. I believe it gives the correct solution:
First off you look for and
.tmpSelectedelements. Then you look for anyulthat only have.selectedelements. The:hasselector looks for the child and I use the:notselector to findulelements. Then I simply grab the childrenselectedelements.jsFiddle