Jack Jack - 3 years ago 170
Javascript Question

javascript select all certain li tags in its subgroup

I got the following html:

<ul class="dropdown-menu inner">
<li class="dropdown-header" data-optgroup="1">Header1</li>
<li class="selected" data-optgroup="1"></li>
<li data-optgroup="1"></li>
<li class="dropdown-header" data-optgroup="2">Header2</li>
<li data-optgroup="2"></li>//note no selected class here
<li data-optgroup="2"></li>
<li class="dropdown-header" data-optgroup="3">Header3</li>
<li class="selected" data-optgroup="3"></li>
<li data-optgroup="3"></li>
</ul>


I need to select all
li
with class
dropdown-header
which have at least 1
li
with class
selected
in its
data-optgroup
subgroup. In this case
Header1
and
Header3
should be selected. I can select all
dropdown-header
li
tags, but I cannot select just those which have at least 1 li with
selected
class in their
data-optgroup
. Any ideas for the solution would be welcome.

Thank you

Answer Source

For each dropdown-header element, you can use nextUntil() to extract the set of li between it and the next one...

var myTags = [];

$('li.dropdown-header').each(function() {
    if ($(this).nextUntil('li.dropdown-header').filter('li.selected').length > 0)
        myTags.push($(this).text());
});

I hope it helps

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download