agyanadda@gmail.com

jQuery Best Practices

jQuery Projects and Best Practices 1 min read Updated Dec 1, 2026 Topic 25 of 25

Write better jQuery

  • Cache selectors: const $menu = $('#menu'); instead of searching again and again
  • Prefix jQuery variables with $ ($menu) so you know they are jQuery objects
  • Chain methods instead of re-selecting
  • Use delegation for lists and tables that change
  • Put code inside $(function () { ... }) or load scripts at the end of the body
  • Prefer classes over many .css() calls
  • Use .text() for user input — .html() can run harmful scripts (XSS)

Performance

  • Use IDs and classes in selectors; avoid very long selectors
  • Build big HTML once, then append it once — not inside a loop
  • Debounce keyup and scroll handlers
  • Use .stop() before repeated animations

Avoid conflicts

If another library uses $, wrap your code:

jQuery(function ($) {
  // $ is safe here
});

WordPress loads jQuery in this "no-conflict" mode.

Common mistakes

  • Loading jQuery twice or after your script
  • Using old methods removed in jQuery 3: .live(), .size(), .bind() (use .on() and .length)
  • Forgetting e.preventDefault() on AJAX forms
  • Missing the CSRF token in Laravel AJAX requests (error 419)

Example

Example — Clean jQuery pattern HTML
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>

<input id="filter" placeholder="Filter courses">
<ul id="courses"></ul>

<script>
  jQuery(function ($) {
    // cache selectors once
    const $list = $('#courses');
    const $filter = $('#filter');
    const courses = ['HTML', 'CSS', 'Bootstrap', 'Tailwind CSS', 'JavaScript', 'jQuery', 'PHP', 'Laravel'];

    // build HTML once, append once
    function render(term) {
      const items = courses
        .filter(c => c.toLowerCase().includes(term))
        .map(c => $('<li>').text(c));
      $list.empty().append(items.length ? items : $('<li>').text('No course found'));
    }

    // debounce the input event
    let timer;
    $filter.on('input', function () {
      clearTimeout(timer);
      const term = $.trim($(this).val()).toLowerCase();
      timer = setTimeout(() => render(term), 200);
    });

    render('');
  });
</script>

Test Yourself With Exercises

Exercise 1 Multiple Choice

Which is the best practice for a selector used many times?

Exercise 2 True / False

.live() still works in jQuery 3.

Exercise 3 Fill in the Blank

Use .___() instead of .html() when inserting user input.

Frequently Asked Questions

Strengthen modern JavaScript (fetch, async/await, modules), then try a framework like Vue or React, or use jQuery skills with Laravel and WordPress projects.