Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hiding an element using jQuery; which method should I use and why?

What is the difference between these two methods?

$("div span").hide();

$("div > span").hide();

Any impact on performance?

like image 949
Jimmy Avatar asked Jan 25 '26 06:01

Jimmy


2 Answers

The first will hide all <span>s found anywhere under the <div>. The second will only hide <span>s that are immediate children of the <div>.

jQuery child-selector

like image 150
Rob Hruska Avatar answered Jan 27 '26 22:01

Rob Hruska


On the performance aspect, it may depend upon the exact HTML, but I found the div > span selector to be about 30% faster in this jsperf test. That may be because it only has to look in the children of each div rather than through the whole DOM.

But, it's probably not enough of a speed difference to matter in most cases.

like image 23
jfriend00 Avatar answered Jan 27 '26 21:01

jfriend00



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!