tags:

views:

31

answers:

3

I have HTML like this:

<div id="best">
    <img src="image.jpg">
    <span>title</span>
    <img src="image.jpg">
    <span>title</span>
    <img src="image.jpg">
    <span>title</span>
</div> 

I want jQuery code to remove all spans. Which is best:

$('#best').find('span').remove();

or

$('#best').children('span').remove();

or

$('#best').find('span').each().remove();

or is there a better solution? Which is best?

A: 

Go for readability:

$('#best > span').remove()
TM
I dont care about readability, only efficiency matters to me. WOuld you say this is the most efficient? Thanks.
JorgeV44
If you benchmark all of these, you'll find that this is as good as any of the examples you provided.
TM
@U22199: You should always care more about readability and maintainability than performance. Premature optimization is, as is often quoted, the root of all evil. Only worry about it if it's causing significant performance issues.
Will Vousden
+3  A: 
$('#best span').remove();
derek
Nice and simple.
Sam
A: 

1 and 3 are identical. 2 is different in that it only removes direct descendants of #best, while the other two will remove descendants at any level. It's really up to you whether you use find or children, as it depends on your intentions, but there's no need for each.

You can, however, contract the whole thing into the selector, so 1 would become $('#best span').remove(); and 2 would become $('#best > span').remove();.

Will Vousden
what would you say about @derek's solution?
JorgeV44
@U22199: See my updated answer.
Will Vousden
Perfect, thanks!
JorgeV44
"You can accept an answer in 7 minutes(click on this box to dismiss)"
JorgeV44