views:

43

answers:

7

The relevant snippet of HTML:

<span class="a">
<div class="fieldname">Question 1</div>
<input type="text" value="" name="q1" />
</span>

The relevant jQuery:

$.each($('.a'), function(){
$thisField = $('.fieldname', $(this));
});

What exactly is being set to $thisField? If my understanding of multiple selectors in jQuery is correct, it should be grabbing the outer <span> element AND the inner <div> element. But for some reason, if I use $thisField.prepend("hi"); it ends up putting hi right before the text Question 1, but not before <div>. I thought multiple selectors would grab both elements, and that prepend() adds hi to the beginning of BOTH elements, not just the <div>

+1  A: 

$('.fieldname', $(this)); is equivalent to $(this).find('.fieldname');

don't get this confused with something like: $('.class1, class2');.

$('.class1, class2'); has only one parameter inputted.

Reigel
so there is a difference betwee $('.class1', '.class2'); and $('.class1', $(this)); and the only difference is that using $(this) as the second means it's shorthand for find() and not a multiple selector? that's the only distinguishing factor?
hatorade
+2  A: 

The calling convention you are using is not a "multiple-selector" it is in fact searching within the context ($(this)) for a selector ('.fieldname'). See docs.

You could do this to get the <div> and the <span>:

$(this).find('.fieldname').andSelf().prepend('hi');
gnarf
A: 

"The .prepend() method inserts the specified content as the first child of each element in the jQuery collection" http://api.jquery.com/prepend/

Since you're targeting all elements with class "fieldname" within an element that has "a" class the output is right.

mamoo
A: 

But for some reason, if I use $thisField.prepend("hi"); it ends up putting hi right before the text Question 1, but not before <div>.

Did you try this?

$.each($('.a'), function(){
  $('hi').insertBefore($('.fieldname', $(this)));
});
Sarfraz
A: 

I'm not sure what you mean with multiple selectors, cause what I see you're doing is just selecting the <div class="fieldname">. All .prepend is doing is adding hi before the content of that div.

So here you're not selecting more than one element.

Eikern
A: 

Multiple selectors work inside the selector string..

like this

$multiple= $('.fieldname, a'); 
// this will select all <a> elements and all elements with class 'fieldname'
Gaby
A: 
$.each($('.a')

means "for each element that has class=a" (in this case, only your span), so if your div also had class=a then you would see the outcome you expected.

David Archer