github

前端发展很快,现代浏览器原生 API 已经足够好用。我们并不需要为了操作 DOM、Event 等再学习一下 jQuery 的 API。同时由于 React、Angular、Vue 等框架的流行,直接操作 DOM 不再是好的模式,jQuery 使用场景大大减少。本项目总结了大部分 jQuery API 替代的方法,暂时只支持 IE10 以上浏览器。

Query Selector

注意:document.querySelectordocument.querySelectorAll 性能很差。如果想提高性能,尽量使用 document.getElementByIddocument.getElementsByClassNamedocument.getElementsByTagName

  • 1.0 选择器查询

  1. // jQuery
  2. $('selector');
  3. // Native
  4. document.querySelectorAll('selector');
  • 1.1 class 查询

  1. // jQuery
  2. $('.class');
  3. // Native
  4. document.querySelectorAll('.class');
  5. // or
  6. document.getElementsByClassName('class');
  1. // jQuery
  2. $('#id');
  3. // Native
  4. document.querySelector('#id');
  5. // or
  6. document.getElementById('id');
  • 1.3 属性查询

  1. // jQuery
  2. $('a[target=_blank]');
  3. // Native
  4. document.querySelectorAll('a[target=_blank]');
  • 1.4 后代查询

  1. // jQuery
  2. $el.find('li');
  3. // Native
  4. el.querySelectorAll('li');
  • 1.5 兄弟及上下元素

  • 兄弟元素
  1. // jQuery
  2. $el.siblings();
  3. // Native - latest, Edge13+
  4. [...el.parentNode.children].filter((child) =>
  5. child !== el
  6. );
  7. // Native (alternative) - latest, Edge13+
  8. Array.from(el.parentNode.children).filter((child) =>
  9. child !== el
  10. );
  11. // Native - IE10+
  12. Array.prototype.filter.call(el.parentNode.children, (child) =>
  13. child !== el
  14. );
  • 上一个元素
  1. // jQuery
  2. $el.prev();
  3. // Native
  4. el.previousElementSibling;
  • 下一个元素
  1. // next
  2. $el.next();
  3. // Native
  4. el.nextElementSibling;


Closest 获得匹配选择器的第一个祖先元素,从当前元素开始沿 DOM 树向上。

  1. // jQuery
  2. $el.closest(queryString);
  3. // Native - Only latest, NO IE
  4. el.closest(selector);
  5. // Native - IE10+
  6. function closest(el, selector) {
  7. const matchesSelector = el.matches || el.webkitMatchesSelector || el.mozMatchesSelector || el.msMatchesSelector;
  8. while (el) {
  9. if (matchesSelector.call(el, selector)) {
  10. return el;
  11. } else {
  12. el = el.parentElement;
  13. }
  14. }
  15. return null;
  16. }
  • 1.7 Parents Until


获取当前每一个匹配元素集的祖先,不包括匹配元素的本身。

  1. // jQuery
  2. $el.parentsUntil(selector, filter);
  3. // Native
  4. function parentsUntil(el, selector, filter) {
  5. const result = [];
  6. const matchesSelector = el.matches || el.webkitMatchesSelector || el.mozMatchesSelector || el.msMatchesSelector;
  7. // match start from parent
  8. el = el.parentElement;
  9. while (el && !matchesSelector.call(el, selector)) {
  10. if (!filter) {
  11. result.push(el);
  12. } else {
  13. if (matchesSelector.call(el, filter)) {
  14. result.push(el);
  15. }
  16. }
  17. el = el.parentElement;
  18. }
  19. return result;
  20. }
  • Input/Textarea ```source-js // jQuery $(‘#my-input’).val();

// Native document.querySelector(‘#my-input’).value;

  1. -
  2. 获取 e.currentTarget `.radio` 中的数组索引
  3. ```source-js
  4. // jQuery
  5. $('.radio').index(e.currentTarget);
  6. // Native
  7. Array.prototype.indexOf.call(document.querySelectorAll('.radio'), e.currentTarget);
  • 1.9 Iframe Contents


jQuery 对象的 iframe contents() 返回的是 iframe 内的 document

  • Iframe contents ```source-js // jQuery $iframe.contents();

// Native iframe.contentDocument;

  1. -
  2. Iframe Query
  3. ```source-js
  4. // jQuery
  5. $iframe.contents().find('.css');
  6. // Native
  7. iframe.contentDocument.querySelectorAll('.css');
  1. // jQuery
  2. $('body');
  3. // Native
  4. document.body;
  • 1.11 获取或设置属性

  • 获取属性 ```source-js // jQuery $el.attr(‘foo’);

// Native el.getAttribute(‘foo’);

  1. -
  2. 设置属性
  3. ```source-js
  4. // jQuery, note that this works in memory without change the DOM
  5. $el.attr('foo', 'bar');
  6. // Native
  7. el.setAttribute('foo', 'bar');
  • 获取 data- 属性 ```source-js // 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. <a name="338d3e6e"></a>
  2. ## CSS & Style
  3. -
  4. <a name="25a5a098"></a>
  5. #### [2.1](https://github.com/nefe/You-Dont-Need-jQuery/blob/master/README.zh-CN.md#2.1) CSS
  6. -
  7. Get style
  8. ```source-js
  9. // jQuery
  10. $el.css("color");
  11. // Native
  12. // 注意:此处为了解决当 style 值为 auto 时,返回 auto 的问题
  13. const win = el.ownerDocument.defaultView;
  14. // null 的意思是不返回伪类元素
  15. win.getComputedStyle(el, null).color;
  • Set style ```source-js // jQuery $el.css({ color: “#ff0011” });

// Native el.style.color = ‘#ff0011’;

  1. -
  2. Get/Set Styles
  3. <br />注意,如果想一次设置多个 style,可以参考 oui-dom-utils [setStyles](https://github.com/oneuijs/oui-dom-utils/blob/master/src/index.js#L194) 方法
  4. -
  5. Add class
  6. ```source-js
  7. // jQuery
  8. $el.addClass(className);
  9. // Native
  10. el.classList.add(className);
  • Remove class ```source-js // jQuery $el.removeClass(className);

// Native el.classList.remove(className);

  1. -
  2. has class
  3. ```source-js
  4. // jQuery
  5. $el.hasClass(className);
  6. // Native
  7. el.classList.contains(className);
  • Toggle class ```source-js // jQuery $el.toggleClass(className);

// Native el.classList.toggle(className);

  1. -
  2. <a name="59bc2075"></a>
  3. #### [2.2](https://github.com/nefe/You-Dont-Need-jQuery/blob/master/README.zh-CN.md#2.2) Width & Height
  4. <br />Width Height 获取方法相同,下面以 Height 为例:
  5. -
  6. Window height
  7. ```source-js
  8. // window height
  9. $(window).height();
  10. // 含 scrollbar
  11. window.document.documentElement.clientHeight;
  12. // 不含 scrollbar,与 jQuery 行为一致
  13. window.innerHeight;
  • Document height ```source-js // 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 );

  1. -
  2. Element height
  3. ```source-js
  4. // jQuery
  5. $el.height();
  6. // Native
  7. function getHeight(el) {
  8. const styles = this.getComputedStyle(el);
  9. const height = el.offsetHeight;
  10. const borderTopWidth = parseFloat(styles.borderTopWidth);
  11. const borderBottomWidth = parseFloat(styles.borderBottomWidth);
  12. const paddingTop = parseFloat(styles.paddingTop);
  13. const paddingBottom = parseFloat(styles.paddingBottom);
  14. return height - borderBottomWidth - borderTopWidth - paddingTop - paddingBottom;
  15. }
  16. // 精确到整数(border-box 时为 height - border 值,content-box 时为 height + padding 值)
  17. el.clientHeight;
  18. // 精确到小数(border-box 时为 height 值,content-box 时为 height + padding + border 值)
  19. el.getBoundingClientRect().height;
  • 2.3 Position & Offset

  • Position
    获得匹配元素相对父元素的偏移 ```source-js // jQuery $el.position();

// Native { left: el.offsetLeft, top: el.offsetTop }

  1. -
  2. Offset
  3. <br />获得匹配元素相对文档的偏移
  4. ```source-js
  5. // jQuery
  6. $el.offset();
  7. // Native
  8. function getOffset (el) {
  9. const box = el.getBoundingClientRect();
  10. return {
  11. top: box.top + window.pageYOffset - document.documentElement.clientTop,
  12. left: box.left + window.pageXOffset - document.documentElement.clientLeft
  13. }
  14. }
  • 2.4 Scroll Top


获取元素滚动条垂直位置。

  1. // jQuery
  2. $(window).scrollTop();
  3. // Native
  4. (document.documentElement && document.documentElement.scrollTop) || document.body.scrollTop;

DOM Manipulation


从 DOM 中移除元素。

  1. // jQuery
  2. $el.remove();
  3. // Native
  4. el.parentNode.removeChild(el);
  5. // Native - Only latest, NO IE
  6. el.remove();
  • Get text
    返回指定元素及其后代的文本内容。 ``` // jQuery $el.text(string);

// Native el.textContent = string;

  1. -
  2. Set text
  3. <br />设置元素的文本内容。
  4. ```source-js
  5. // jQuery
  6. $el.text(string);
  7. // Native
  8. el.textContent = string;
  • Get HTML ```source-js // jQuery $el.html();

// Native el.innerHTML;

  1. -
  2. Set HTML
  3. ```source-js
  4. // jQuery
  5. $el.html(htmlString);
  6. // Native
  7. el.innerHTML = htmlString;


Append 插入到子节点的末尾

  1. // jQuery
  2. $el.append("<div id='container'>hello</div>");
  3. // Native (HTML string)
  4. el.insertAdjacentHTML('beforeend', '<div id="container">Hello World</div>');
  5. // Native (Element)
  6. el.appendChild(newEl);
  1. // jQuery
  2. $el.prepend("<div id='container'>hello</div>");
  3. // Native (HTML string)
  4. el.insertAdjacentHTML('afterbegin', '<div id="container">Hello World</div>');
  5. // Native (Element)
  6. el.insertBefore(newEl, el.firstChild);
  • 3.6 insertBefore


在选中元素前插入新节点

  1. // jQuery
  2. $newEl.insertBefore(queryString);
  3. // Native (HTML string)
  4. el.insertAdjacentHTML('beforebegin ', '<div id="container">Hello World</div>');
  5. // Native (Element)
  6. const el = document.querySelector(selector);
  7. if (el.parentNode) {
  8. el.parentNode.insertBefore(newEl, el);
  9. }
  • 3.7 insertAfter


在选中元素后插入新节点

  1. // jQuery
  2. $newEl.insertAfter(queryString);
  3. // Native (HTML string)
  4. el.insertAdjacentHTML('afterend', '<div id="container">Hello World</div>');
  5. // Native (Element)
  6. const el = document.querySelector(selector);
  7. if (el.parentNode) {
  8. el.parentNode.insertBefore(newEl, el.nextSibling);
  9. }


如果匹配给定的选择器,返回true

  1. // jQuery
  2. $el.is(selector);
  3. // Native
  4. el.matches(selector);


深拷贝被选元素。(生成被选元素的副本,包含子节点、文本和属性。)

  1. //jQuery
  2. $el.clone();
  3. //Native
  4. el.cloneNode();

//深拷贝添加参数‘true’ ```


移除所有子节点

  1. //jQuery
  2. $el.empty();
  3. //Native
  4. el.innerHTML = '';

把每个被选元素放置在指定的HTML结构中。

  1. //jQuery
  2. $(".inner").wrap('<div class="wrapper"></div>');
  3. //Native
  4. Array.prototype.forEach.call(document.querySelector('.inner'), (el) => {
  5. const wrapper = document.createElement('div');
  6. wrapper.className = 'wrapper';
  7. el.parentNode.insertBefore(wrapper, el);
  8. el.parentNode.removeChild(el);
  9. wrapper.appendChild(el);
  10. });


移除被选元素的父元素的DOM结构

  1. // jQuery
  2. $('.inner').unwrap();
  3. // Native
  4. Array.prototype.forEach.call(document.querySelectorAll('.inner'), (el) => {
  5. let elParentNode = el.parentNode
  6. if(elParentNode !== document.body) {
  7. elParentNode.parentNode.insertBefore(el, elParentNode)
  8. elParentNode.parentNode.removeChild(elParentNode)
  9. }
  10. });


用指定的元素替换被选的元素

  1. //jQuery
  2. $('.inner').replaceWith('<div class="outer"></div>');
  3. //Native
  4. Array.prototype.forEach.call(document.querySelectorAll('.inner'),(el) => {
  5. const outer = document.createElement("div");
  6. outer.className = "outer";
  7. el.parentNode.insertBefore(outer, el);
  8. el.parentNode.removeChild(el);
  9. });

解析 HTML/SVG/XML 字符串

  1. // jQuery
  2. $(`<ol>
  3. <li>a</li>
  4. <li>b</li>
  5. </ol>
  6. <ol>
  7. <li>c</li>
  8. <li>d</li>
  9. </ol>`);
  10. // Native
  11. range = document.createRange();
  12. parse = range.createContextualFragment.bind(range);
  13. parse(`<ol>
  14. <li>a</li>
  15. <li>b</li>
  16. </ol>
  17. <ol>
  18. <li>c</li>
  19. <li>d</li>
  20. </ol>`);

Ajax

Fetch API 是用于替换 XMLHttpRequest 处理 ajax 的新标准,Chrome 和 Firefox 均支持,旧浏览器可以使用 polyfills 提供支持。

IE9+ 请使用 github/fetch,IE8+ 请使用 fetch-ie8,JSONP 请使用 fetch-jsonp

  • 4.1 从服务器读取数据并替换匹配元素的内容。

  1. // jQuery
  2. $(selector).load(url, completeCallback)
  3. // Native
  4. fetch(url).then(data => data.text()).then(data => {
  5. document.querySelector(selector).innerHTML = data
  6. }).then(completeCallback)

Events

完整地替代命名空间和事件代理,链接到 https://github.com/oneuijs/oui-dom-events

  • 5.0 Document ready by DOMContentLoaded

  1. // jQuery
  2. $(document).ready(eventHandler);
  3. // Native
  4. // 检测 DOMContentLoaded 是否已完成
  5. if (document.readyState !== 'loading') {
  6. eventHandler();
  7. } else {
  8. document.addEventListener('DOMContentLoaded', eventHandler);
  9. }
  • 5.1 使用 on 绑定事件

  1. // jQuery
  2. $el.on(eventName, eventHandler);
  3. // Native
  4. el.addEventListener(eventName, eventHandler);
  • 5.2 使用 off 解绑事件 ```source-js // jQuery $el.off(eventName, eventHandler);

// Native el.removeEventListener(eventName, eventHandler);

  1. -
  2. <a name="6e6b21cb"></a>
  3. #### [5.3](https://github.com/nefe/You-Dont-Need-jQuery/blob/master/README.zh-CN.md#5.3) Trigger
  4. ```source-js
  5. // jQuery
  6. $(el).trigger('custom-event', {key1: 'data'});
  7. // Native
  8. if (window.CustomEvent) {
  9. const event = new CustomEvent('custom-event', {detail: {key1: 'data'}});
  10. } else {
  11. const event = document.createEvent('CustomEvent');
  12. event.initCustomEvent('custom-event', true, true, {key1: 'data'});
  13. }
  14. el.dispatchEvent(event);

Utilities

大部分实用工具都能在 native API 中找到. 其他高级功能可以选用专注于该领域的稳定性和性能都更好的库来代替,推荐 lodash

  • 6.1 基本工具

  • isArray
  1. // jQuery
  2. $.isArray(range);
  3. // Native
  4. Array.isArray(range);
  • isWindow
  1. // jQuery
  2. $.isWindow(obj);
  3. // Native
  4. function isWindow(obj) {
  5. return obj !== null && obj !== undefined && obj === obj.window;
  6. }
  • inArray
  1. // jQuery
  2. $.inArray(item, array);
  3. // Native
  4. array.indexOf(item) > -1;
  5. // ES6-way
  6. array.includes(item);
  • isNumeric

`typeof``type````source-js // jQuery $.isNumeric(item);

// Native function isNumeric(n) { return !isNaN(parseFloat(n)) && isFinite(n); }

  1. - isFunction
  2. ```source-js
  3. // jQuery
  4. $.isFunction(item);
  5. // Native
  6. function isFunction(item) {
  7. if (typeof item === 'function') {
  8. return true;
  9. }
  10. var type = Object.prototype.toString(item);
  11. return type === '[object Function]' || type === '[object GeneratorFunction]';
  12. }
  • isEmptyObject
  1. // jQuery
  2. $.isEmptyObject(obj);
  3. // Native
  4. function isEmptyObject(obj) {
  5. return Object.keys(obj).length === 0;
  6. }
  • isPlainObject
  1. // jQuery
  2. $.isPlainObject(obj);
  3. // Native
  4. function isPlainObject(obj) {
  5. if (typeof (obj) !== 'object' || obj.nodeType || obj !== null && obj !== undefined && obj === obj.window) {
  6. return false;
  7. }
  8. if (obj.constructor &&
  9. !Object.prototype.hasOwnProperty.call(obj.constructor.prototype, 'isPrototypeOf')) {
  10. return false;
  11. }
  12. return true;
  13. }
  • extend

polyfill```source-js // jQuery $.extend({}, defaultOpts, opts);

// Native Object.assign({}, defaultOpts, opts);

  1. - trim
  2. ```source-js
  3. // jQuery
  4. $.trim(string);
  5. // Native
  6. string.trim();
  • map
  1. // jQuery
  2. $.map(array, (value, index) => {
  3. });
  4. // Native
  5. array.map((value, index) => {
  6. });
  • each
  1. // jQuery
  2. $.each(array, (index, value) => {
  3. });
  4. // Native
  5. array.forEach((value, index) => {
  6. });
  • grep
  1. // jQuery
  2. $.grep(array, (value, index) => {
  3. });
  4. // Native
  5. array.filter((value, index) => {
  6. });
  • type
  1. // jQuery
  2. $.type(obj);
  3. // Native
  4. function type(item) {
  5. const reTypeOf = /(?:^\[object\s(.*?)\]$)/;
  6. return Object.prototype.toString.call(item)
  7. .replace(reTypeOf, '$1')
  8. .toLowerCase();
  9. }
  • merge
  1. // jQuery
  2. $.merge(array1, array2);
  3. // Native
  4. // 使用 concat,不能去除重复值
  5. function merge(...args) {
  6. return [].concat(...args)
  7. }
  8. // ES6,同样不能去除重复值
  9. array1 = [...array1, ...array2]
  10. // 使用 Set,可以去除重复值
  11. function merge(...args) {
  12. return Array.from(new Set([].concat(...args)))
  13. }
  • now
  1. // jQuery
  2. $.now();
  3. // Native
  4. Date.now();
  • proxy
  1. // jQuery
  2. $.proxy(fn, context);
  3. // Native
  4. fn.bind(context);
  • makeArray
  1. // jQuery
  2. $.makeArray(arrayLike);
  3. // Native
  4. Array.prototype.slice.call(arrayLike);
  5. // ES6-way
  6. Array.from(arrayLike);


检测 DOM 元素是不是其他 DOM 元素的后代.

  1. // jQuery
  2. $.contains(el, child);
  3. // Native
  4. el !== child && el.contains(child);
  • 6.3 Globaleval


全局执行 JavaScript 代码。

  1. // jQuery
  2. $.globaleval(code);
  3. // Native
  4. function Globaleval(code) {
  5. const script = document.createElement('script');
  6. script.text = code;
  7. document.head.appendChild(script).parentNode.removeChild(script);
  8. }
  9. // Use eval, but context of eval is current, context of $.Globaleval is global.
  10. eval(code);
  • parseHTML
  1. // jQuery
  2. $.parseHTML(htmlString);
  3. // Native
  4. function parseHTML(string) {
  5. const context = document.implementation.createHTMLDocument();
  6. // Set the base href for the created document so any parsed elements with URLs
  7. // are based on the document's URL
  8. const base = context.createElement('base');
  9. base.href = document.location.href;
  10. context.head.appendChild(base);
  11. context.body.innerHTML = string;
  12. return context.body.children;
  13. }
  • parseJSON
  1. // jQuery
  2. $.parseJSON(str);
  3. // Native
  4. JSON.parse(str);

Animation

  • 8.1 Show & Hide

  1. // jQuery
  2. $el.show();
  3. $el.hide();
  4. // Native
  5. // 更多 show 方法的细节详见 https://github.com/oneuijs/oui-dom-utils/blob/master/src/index.js#L363
  6. el.style.display = ''|'inline'|'inline-block'|'inline-table'|'block';
  7. el.style.display = 'none';


显示或隐藏元素。

  1. // jQuery
  2. $el.toggle();
  3. // Native
  4. if (el.ownerDocument.defaultView.getComputedStyle(el, null).display === 'none') {
  5. el.style.display = ''|'inline'|'inline-block'|'inline-table'|'block';
  6. } else {
  7. el.style.display = 'none';
  8. }
  • 8.3 FadeIn & FadeOut

  1. // jQuery
  2. $el.fadeIn(3000);
  3. $el.fadeOut(3000);
  4. // Native
  5. el.style.transition = 'opacity 3s';
  6. // fadeIn
  7. el.style.opacity = '1';
  8. // fadeOut
  9. el.style.opacity = '0';


调整元素透明度。

  1. // jQuery
  2. $el.fadeTo('slow',0.15);
  3. // Native
  4. el.style.transition = 'opacity 3s'; // 假设 'slow' 等于 3 秒
  5. el.style.opacity = '0.15';
  • 8.5 FadeToggle


动画调整透明度用来显示或隐藏。

  1. // jQuery
  2. $el.fadeToggle();
  3. // Native
  4. el.style.transition = 'opacity 3s';
  5. const { opacity } = el.ownerDocument.defaultView.getComputedStyle(el, null);
  6. if (opacity === '1') {
  7. el.style.opacity = '0';
  8. } else {
  9. el.style.opacity = '1';
  10. }
  • 8.6 SlideUp & SlideDown

  1. // jQuery
  2. $el.slideUp();
  3. $el.slideDown();
  4. // Native
  5. const originHeight = '100px';
  6. el.style.transition = 'height 3s';
  7. // slideUp
  8. el.style.height = '0px';
  9. // slideDown
  10. el.style.height = originHeight;
  • 8.7 SlideToggle


滑动切换显示或隐藏。

  1. // jQuery
  2. $el.slideToggle();
  3. // Native
  4. const originHeight = '100px';
  5. el.style.transition = 'height 3s';
  6. const { height } = el.ownerDocument.defaultView.getComputedStyle(el, null);
  7. if (parseInt(height, 10) === 0) {
  8. el.style.height = originHeight;
  9. }
  10. else {
  11. el.style.height = '0px';
  12. }


执行一系列 CSS 属性动画。

  1. // jQuery
  2. $el.animate({ params }, speed);
  3. // Native
  4. el.style.transition = 'all ' + speed;
  5. Object.keys(params).forEach((key) =>
  6. el.style[key] = params[key];