Iterate over parent elements based on values of child elements
This seems like a really simple thing but I haven't figured out how to do it. Given XML snippet:
<programs>
<program>
<title>Program 1</title>
<time>2011-01-05 12:00:00</time>
<code>a</code>
</program>
<program>
<title>Program 2</title>
<time>2011-01-05 12:30:00</time>
<code>b</code>
</program>
<program>
<title>Program 1</title>
<time>2011-01-06 12:00:00</time>
<code>a</code>
</program>
</programs>
How do I iterate over where starts with '2011-01-05' and code equals a? I know how to do this for one element and I have seemingly written code that will do either/or but I can't hit on the right syntax for AND logic.
if the variable data contains my XML then I can use $(data).find("code:contentIs('a'),time:contains('2011-01-05')").parent()
to get both Program 1 and Program 2 but I only want to get Program 1.
(contentIs is a function I wrote that I know works so don't pay attention to that)
I tried $(data).find("code:contentIs('a'):time:cont开发者_如何学Cains('2011-01-05')").parent()
but I get Syntax error, unrecognized expression: time
I feel like I've gotta be missing some basic syntax here but I can't figure out what it is.
I'd use :has
here. It finds elements that have descendant elements that match a selector.
$(data).find('program:has(code:contentIs("a")):has(time:contains("2011-01-05"))');
Using the has
selector twice says "ensure the element matches both requirements". This is the same as selecting by two classes, e.g. a.someClass.someOtherClass
.
精彩评论