'jquery selector to find a child element with
Have been googling and trial-and-erroring for an hour trying to come up with a jquery selector to access one of several label elements in an expandable tree. The html is either like this:
<span id="ppown" class="treeTitleSpan" role="leaf">PPO</span>
<span class="treeCheckBoxLabel">
<label class='nodeCheckIcon' />
Or like this:
<span id="ppw" class="treeTitleSpan" role="leaf">Other</span>
<span class="handle closed"></span>
<span class="treeCheckBoxLabel">
<label class='nodeCheckIcon' />
And I am starting from the .treeTitleSpan span in each case (in a click handler). I know I can access one with:
$(this).next().next().children('.nodeCheckIcon');
And the other with:
$(this).next().children('.nodeCheckIcon');
But I would like a single selector that will work for both cases, 'find' doesn't seem to work:
$(this).find('.nodeCheckIcon:first')
Any help would be appreciated.
rick
Solution 1:[1]
$(this).nextAll('.treeCheckBoxLabel').children('.nodeCheckIcon');
Or if you might have more than one Label like:
<span id="ppw" class="treeTitleSpan" role="leaf">Other</span>
<span class="handle closed"></span>
<span class="treeCheckBoxLabel">
<label class='nodeCheckIcon' />
</span>
<span class="treeCheckBoxLabel">
<label class='nodeCheckIcon' />
</span>
And you only want the first one:
$(this).nextAll('.treeCheckBoxLabel').first().children('.nodeCheckIcon');
Solution 2:[2]
How about something like this:
$(this).nextAll('.treeCheckBoxLabel:first').children('.nodeCheckIcon');
Using :first ensures you'll only select one .treeCheckBoxLabel at most, which may or may not be an issue depending on the rest of your HTML.
Solution 3:[3]
Alternative to the other posts (many ways to skin a cat :))
$(this).siblings(".treeCheckBoxLabel:has(label.nodeCheckIcon):first")
Solution 4:[4]
Since this is pointing to the span element which is the sibling of the parent of label, $(this).find('.nodeCheckIcon:first') is not going to work. I dont know about your complete markup structure, but if you have a wrapping container for this span element then you can try this
$(this).parent().find('.nodeCheckIcon:first');
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Paul |
| Solution 2 | Ken Redler |
| Solution 3 | Jules |
| Solution 4 | ShankarSangoli |
