0

I have a little problem in my jQuery code. I do things like that:

HTML :

<div class="parent">
    <div class="selector">....</div>
</div>

JS:

$ref = $('.parent .selector');
$parent = $('.parent');

$ref.size() --> 1 
$parent.append('<div class="selector">....</div>');
$ref.size() --> always 1  ...

So what the use of store in vars... If i don't use reference var, all is good. Thanks.

2
  • 1
    Caching the result is only good when you do not add or remove elements dynamically. If you do, the set of elements that matchs the selector is no longer the same, and it then makes sense to query again. Commented Jul 16, 2013 at 13:16
  • jQuery only selects the elements that currently exist. If you change the structure of the document, you have to reselect the elements. Commented Jul 16, 2013 at 13:21

2 Answers 2

2

By the time you store the object in $ref it only has one child so it will always show 1
You have to go through the DOM again after appending a new item.

$ref = $('.parent .selector');
$parent = $('.parent');

$ref.size() --> 1 
$parent.append('<div class="selector">....</div>');
$('.parent .selector').size() --> 2
Sign up to request clarification or add additional context in comments.

Comments

0

Put like

$('<div class="selector">....</div>').appendTo($parent);
$parent.size(); --> gives 2

You need to append the div after the div class selector

7 Comments

Both are same I think...See iam appending to $ref
Excuse me but this is not the correct use of append in jQuery.
I know, i'm just giving the other method for a more global view.
Won't that append .selector into .selector instead of parent?
Yes it will add to every element in the collection actually, i didn't even see that
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.