tags:

views:

219

answers:

3

I'm trying to traverse an xml document. This doesn't work (zero results):

jquery("foo bar")

this does work:

jquery("foo").find("bar")

any idea why?

+2  A: 
jquery("foo bar")

the first one looks for bar element to be a descendent of foo element

so it would work in this example

 <foo>
  <div>Form is surrounded by the green outline</div>
  <label>Child:</label>
  <bar name="thisone" />
  <fieldset>
    <label>Grandchild:</label>
    <bar name="thisone2" />
  </fieldset>
 </foo>

This one does searching using a jquery expression

jquery("foo").find("bar")

Starts with all foo elements and searches for descendant bar elements

so it would work in this example

<foo><bar>found</bar>, not here?</foo>
<foo>not here <bar>found</bar>.</foo>

so without your markup can't really specify your problem

TStamper
My understanding is that both of the examples should have exactly the same results. I believe that's pretty much what you're saying.
morgancodes
yea, unless you did this way jquery("foo > bar") there should be no difference
TStamper
A: 

I was curious how you got conflicting results, so I experimented with markup but couldn't think of a way to reproduce the behavior you describe returned by the jQuery object itself. I did find some slightly different situations that produce such behavior, such as:

<div>
    <span id="span1">Hello World</span>
    <img src="foo" alt="bar" />
</div>

If you try this syntax (here I am spelling out "jQuery" rather than using "$")

jQuery("#span1").parents("div img").css("max-width","25%");  // no good

then you will get no result, because "span1" does not have a "div img" parent, just a "div" parent. But this will produce a result:

jQuery("#span1").parents("div").find("img").css("max-width","25%");  // will work

because it locates the parent div of "span1" and from there finds the image that is a descendant of that parent div.

But my example is a contrived one, because in that situation you would probably just use

jQuery("#span1").siblings("img").css("max-width","25%");  // will also work, and is clearer
Paul
A: 

The important thing to note is that you are traversing XML. While your examples are valid and equal for HTML, I've found, at least on IE, that descendant expressions don't work on XML.

In fact, I'd be grateful if someone could confirm and explain this.

Jeff Meatball Yang