Baike.dev
All toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
Y

You-Dont-Need-jQuery

> 编程语言
Open source

Examples of how to do query, style, dom, ajax, event etc like jQuery with plain javascript.

20.1K stars0 likes1 views
WebsiteGitHub

About

Examples of how to do query, style, dom, ajax, event etc like jQuery with plain javascript.

You (Might) Don't Need jQuery

Frontend environments evolve rapidly nowadays and modern browsers have already implemented a great deal of DOM/BOM APIs which are good enough for production use. We don't have to learn jQuery from scratch for DOM manipulation or event handling. In the meantime, thanks to the spread of frontend libraries such as React, Angular and Vue, manipulating the DOM directly becomes anti-pattern, so that jQuery usage has never been less important. This project summarizes most of the alternatives in native Javascript implementation to jQuery methods, with IE 10+ support.

ℹ️ Notice:

  1. jQuery is still a great library and has many valid use cases. Don’t migrate away if you don’t want to!
  2. The alternatives are not completely equivalent in all scenarios, and it is recommended that you test it before using it.

Table of Contents

  1. Translations
  2. Query Selector
  3. CSS & Style
  4. DOM Manipulation
  5. Ajax
  6. Events
  7. Utilities
  8. Promises
  9. Animation
  10. Alternatives
  11. Browser Support

Translations

  • 한국어
  • 正體中文
  • 简体中文
  • Bahasa Melayu
  • Bahasa Indonesia
  • Português(PT-BR)
  • Tiếng Việt Nam
  • Español
  • Русский
  • Кыргызча
  • Türkçe
  • Italiano
  • Français
  • 日本語
  • Polski

Query Selector

In place of common selectors like class, id or attribute we can use document.querySelector or document.querySelectorAll for substitution. The differences lie in:

  • document.querySelector returns the first matched element
  • document.querySelectorAll returns all matched elements as NodeList. It can be converted to Array using Array.prototype.slice.call(document.querySelectorAll(selector)); or any of the methods outlined in makeArray
  • If there are no elements matched, jQuery and document.querySelectorAll will return [], whereas document.querySelector will return null.

Notice: document.querySelector and document.querySelectorAll are quite SLOW, thus try to use document.getElementById, document.getElementsByClassName or document.getElementsByTagName if you want to get a performance bonus.

  • 1.0 Query by selector

    // jQuery
    $('selector');
    
    // Native
    document.querySelectorAll('selector');
    
  • 1.1 Query by class

    // jQuery
    $('.class');
    
    // Native
    document.querySelectorAll('.class');
    
    // or
    document.getElementsByClassName('class');
    
  • 1.2 Query by id

    // jQuery
    $('#id');
    
    // Native
    document.querySelector('#id');
    
    // or
    document.getElementById('id');
    
    // or
    window['id']
    
  • 1.3 Query by attribute

    // jQuery
    $('a[target=_blank]');
    
    // Native
    document.querySelectorAll('a[target=_blank]');
    
  • 1.4 Query in descendants

    // jQuery
    $el.find('li');
    
    // Native
    el.querySelectorAll('li');
    
  • 1.5 Sibling/Previous/Next Elements

    • All siblings

      // jQuery
      $el.siblings();
      
      // Native - latest, Edge13+
      [...el.parentNode.children].filter((child) =>
        child !== el
      );
      // Native (alternative) - latest, Edge13+
      Array.from(el.parentNode.children).filter((child) =>
        child !== el
      );
      // Native - IE10+
      Array.prototype.filter.call(el.parentNode.children, (child) =>
        child !== el
      );
      
    • Previous sibling

      // jQuery
      $el.prev();
      
      // Native
      el.previousElementSibling;
      
    • Next sibling

      // jQuery
      $el.next();
      
      // Native
      el.nextElementSibling;
      
    • All previous siblings

      // jQuery (optional filter selector)
      $el.prevAll($filter);
      
      // Native (optional filter function)
      function getPreviousSiblings(elem, filter) {
        var sibs = [];
        while (elem = elem.previousSibling) {
            if (elem.nodeType === 3) continue; // ignore text nodes
            if (!filter || filter(elem)) sibs.push(elem);
        }
        return sibs;
      }
      
    • All next siblings

…

js function exampleFilter(elem) { switch (elem.nodeName.toUpperCase()) { case 'DIV': return true; case 'SPAN': return true; default: return false; } }


- [1.6](#1.6) <a name='1.6'></a> Closest

  Return the first matched element by provided selector, traversing from current element up through its ancestors in the DOM tree.

  ```js
  // jQuery
  $el.closest(selector);

  // Native - Only latest, NO IE
  el.closest(selector);

  // Native - IE10+
  function closest(el, selector) {
    const matchesSelector = el.matches || el.webkitMatchesSelector || el.mozMatchesSelector || el.msMatchesSelector;

    while (el) {
      if (matchesSelector.call(el, selector)) {
        return el;
      } else {
        el = el.parentElement;
      }
    }
    return null;
  }
  • 1.7 Parents Until

    Get the ancestors of each element in the current set of matched elements, up to but not including the element matched by the selector, DOM node, or jQuery object.

    // jQuery
    $el.parentsUntil(selector, filter);
    
    // Native
    function parentsUntil(el, selector, filter) {
      const result = [];
      const matchesSelector = el.matches || el.webkitMatchesSelector || el.mozMatchesSelector || el.msMatchesSelector;
    
      // match start from parent
      el = el.parentElement;
      while (el && !matchesSelector.call(el, selector)) {
        if (!filter) {
          result.push(el);
        } else {
          if (matchesSelector.call(el, filter)) {
            result.push(el);
          }
        }
        el = el.parentElement;
      }
      return result;
    }
    
  • 1.8 Form

    • Input/Textarea

      // jQuery
      $('#my-input').val();
      
      // Native
      document.querySelector('#my-input').value;
      
    • Get index of e.currentTarget between .radio

      // jQuery
      $('.radio').index(e.currentTarget);
      
      // Native
      Array.from(document.querySelectorAll('.radio')).indexOf(e.currentTarget);
      or
      Array.prototype.indexOf.call(document.querySelectorAll('.radio'), e.currentTarget);
      
  • 1.9 Iframe Contents

    $('iframe').contents() returns contentDocument for this specific iframe

    • Iframe contents

      // jQuery
      $iframe.contents();
      
      // Native
      iframe.contentDocument;
      
    • Iframe Query

      // jQuery
      $iframe.contents().find('.css');
      
      // Native
      iframe.contentDocument.querySelectorAll('.css');
      
  • 1.10 Get body

    // jQuery
    $('body');
    
    // Native
    document.body;
    
  • 1.11 Attribute getter and setter

    • Get an attribute

      // jQuery
      $el.attr('foo');
      
      // Native
      el.getAttribute('foo');
      
    • Set an attribute

      // jQuery
      $el.attr('foo', 'bar');
      
      // Native
      el.setAttribute('foo', 'bar');
      
    • Get a data- attribute

      // jQuery
      $el.data('foo');
      
      // Native (use `getAttribute`)
      el.getAttribute('data-foo');
      
      // Native (use `dataset` if only need to support IE 11+)
      el.dataset['foo'];
      
  • 1.12 Selector containing string (case-sensitive)

    // jQuery
    $("selector:contains('text')");
    
    // Native
    function contains(selector, text) {
      var elements = document.querySelectorAll(selector);
      return Array.from(elements).filter(function(element) {
        return RegExp(text).test(element.textContent);
      });
    }
    

⬆ back to top

CSS & Style

  • 2.1 CSS

    • Get style

      // jQuery
      $el.css('color');
      
      // Native
      // NOTE: Known bug, will return 'auto' if style value is 'auto'
      const win = el.ownerDocument.defaultView;
      
      // null means not to return pseudo styles
      win.getComputedStyle(el, null).color;
      
    • Set style

      // jQuery
      $el.css({ color: '#f01' });
      
      // Native
      el.style.color = '#f01';
      
    • Get/Set Styles

      // jQuery
      $el.css({ color: '#f01', 'border-color': '#f02' })
      
      // Native
      Object.assign(el.style, { color: '#f01', borderColor: '#f02' }) 
      
    • Add class

      // jQuery
      $el.addClass(className);
      
      // Native
      el.classList.add(className);
      
    • Remove class

      // jQuery
      $el.removeClass(className);
      
      // Native
      el.classList.remove(className);
      
    • has class

      // jQuery
      $el.hasClass(className);
      
      // Native
      el.classList.contains(className);
      
    • Toggle class

      // jQuery
      $el.toggleClass(className);
      
      // Native
      el.classList.toggle(className);
      
  • 2.2 Width & Height

    Width and Height are theoretically identical, take Height as example:

    • Window height

      // window height
      $(window).height();
      
      // without scrollbar, behaves like jQuery
      window.document.documentElement.clientHeight;
      
      // with scrollbar
      window.innerHeight;
      
    • Document height

      // jQuery
      $(document).height();
      
      // Native
      const body = document.body;
      const html = document.documentElement;
      const height = Math.max(
        body.offsetHeight,
        body.scrollHeight,
        html.clientHeight,
        html.offsetHeight,
        html.scrollHeight
      );
      
    • Element height

      // jQuery
      $el.height();
      
      // Native
      function getHeight(el) {
        const styles = window.getComputedStyle(el);
        const height = el.offsetHeight;
        const borderTopWidth = parseFloat(styles.borderTopWidth);
        const borderBottomWidth = parseFloat(styles.borderBottomWidth);
        const paddingTop = parseFloat(styles.paddingTop);
        const paddingBottom = parseFloat(styles.paddingBottom);
        return height - borderBottomWidth - borderTopWidth - paddingTop - paddingBottom;
      }
      
      // accurate to integer(when `border-box`, it's `height - border`; when `content-box`, it's `height + padding`)
      el.clientHeight;
      
      // accurate to decimal(when `border-box`, it's `height`; when `content-box`, it's `height + padding + border`)
      el.getBoundingClientRect().height;
      
  • 2.3 Position & Offset

    • Position

      Get the current coordinates of the element relative to the offset parent.

      // jQuery
      $el.position();
      
      // Native
      { left: el.offsetLeft, top: el.offsetTop }
      
    • Offset

      Get the current coordinates of the element relative to the document.

      // jQuery
      $el.offset();
      
      // Native
      function getOffset (el) {
        const box = el.getBoundingClientRect();
      
        return {
          top: box.top + window.pageYOffset - document.documentElement.clientTop,
          left: box.left + window.pageXOffset - document.documentElement.clientLeft
        };
      }
      
  • 2.4 Scroll Top

    Get the current vertical position of the scroll bar for the element.

    // jQuery
    $(window).scrollTop();
    
    // Native
    (document.documentElement && document.documentElement.scrollTop) || document.body.scrollTop;
    

⬆ back to top

DOM Manipulation

  • 3.1 Remove

    Remove the element from the DOM.

    // jQuer
    

GitHub Issues· 3 open

View all on GitHub
  • #259

    Native append() and prepend() handle strings as text nodes

    Updated Jun 11, 2026
  • #246

    Array.prototype.includes() does not return the index, but boolean

    Updated Jan 26, 2024
  • #255

    outerWidth?

    Updated Jul 19, 2022

Highlights

  • •Bahasa Melayu
  • •Bahasa Indonesia
  • •Português(PT-BR)
  • •Tiếng Việt Nam
  • •Кыргызча
  • •Italiano
  • •Français
  • •document.querySelector returns the first matched element
  • •If there are no elements matched, jQuery and document.querySelectorAll will return [], whereas document.querySelector will return null.
  • •1.0 <a name='1.0'></a> Query by selector

> Tags

JavaScript

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category编程语言
PricingOpen source

> Related tools

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言