Pavel Staselun
Pavel Staselun

Reputation: 2010

jQuery more complicated selector vs. each element processing

I'm using ez-checkbox plugin, which simply wraps a checkbox into a div so checkboxes look better.

<div class="ez-checkbox ez-checked">
  <input type="checkbox" checked autocomplete="off" class="ezmark ez-hide ez-init">
</div>

So I have many of these and I want check them all on click. Which of these click handlers is the best from the performance point of view:

First - find all inputs, filter out already checked ones, trigger click event for each element so that plugin done its job.

oPhotos
    .find('input')
        .not(':checked')
        .each(function() {
            $(this).click();
        });

Second - same as first, but we do the "checking" job ourselves.

oPhotos
    .find('input')
        .not(':checked')
        .each(function() {
            $(this)
                .prop('checked', true)
                .parent()
                    .addClass('ez-checked');
        });

Third - loop all checkboxes, if current is not checked - trigger the click.

oPhotos
    .find('input')
        .each(function() {
            if (! $(this).is(':checked')) $(this).click();
        });

Fourth - loop all checkboxes, if current is not checked - do the "checking" job ourselves.

oPhotos
    .find('input')
        .each(function() {
            if (! $(this).is(':checked')) {
                $(this)
                    .prop('checked', true)
                    .parent()
                        .addClass('ez-checked');
            }
        });

Upvotes: 3

Views: 440

Answers (1)

Pavel Staselun
Pavel Staselun

Reputation: 2010

I've run performance tests. Turns out that using more complicated selectors + filtering items using .not() + handling events instead of triggering them is the fastest option. The worst option is to loop all elements to filter them and trigger an event.

Upvotes: 2

Related Questions