简体   繁体   中英

children vs selector - jQuery

For the sake of simplicity I'll narrow down the question as below. I have a large code running in the click js functions. To represent that All I have added an alert()

HTML

<ul>
  <li>Test li 1</li>
  <li>Test li 2</li>
  <li>Test li 3</li>
  <li>Test li 4</li>
  <li>Test li 5</li>
</ul>

JS

Method 1

$('ul li').click(function(){alert('hi');});

Method 2

$('ul').children().click(function(){alert('hi');});

Method 1 and method 2 both works fine.

Which one is better ? Is it better to use the selector or use the children method ? What's the purpose of having a children method when we can use selector?

Test Fiddle

I'm just grabbing the basics and hope not knowing something is not a crime. Thanks

While both of those pieces of code work correctly on the sample HTML they are not identical.

.children returns all child elements (whether they are an "li" or not).

"ul li" as a selector returns all "li" descendants of the "ul" whether they are children or not.

These two are equivalent and select only "li" children of the "ul" parent:

$('ul > li').click(function(){alert('hi');});
$('ul').children("li").click(function(){alert('hi');});

As for which is better (the original question), there is no real answer for this I suspect and will depend on your actual requirements and html (when you ask for which is 'better' what do you mean? Performance? Maintainability?).

Usually the former will use the CSS selector engine of the browser where the selector you are using is supported, and the later will always use jquery built code (I think) so I would go for the former in most cases.

as to

Which one is better ?..

updated

actually, it depends on the HTML structure... if incase, you have small number of <li> 's in ul (first level) going with children selector is better

you can check this in js.perf... link here

but if you have large number of <li> (in first level) the children selector gets slower ..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM