File: README.md
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:
- jQuery is still a great library and has many valid use cases. Don’t migrate away if you don’t want to!
- The alternatives are not completely equivalent in all scenarios, and it is recommended that you test it before using it.
Table of Contents
- Translations
- Query Selector
- CSS & Style
- DOM Manipulation
- Ajax
- Events
- Utilities
- Promises
- Animation
- Alternatives
- 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.querySelectorreturns the first matched elementdocument.querySelectorAllreturns all matched elements as NodeList. It can be converted to Array usingArray.prototype.slice.call(document.querySelectorAll(selector));or any of the methods outlined in makeArray- If there are no elements matched, jQuery and
document.querySelectorAllwill return[], whereasdocument.querySelectorwill returnnull.
Notice:
document.querySelectoranddocument.querySelectorAllare quite SLOW, thus try to usedocument.getElementById,document.getElementsByClassNameordocument.getElementsByTagNameif you want to get a performance bonus.
1.0 Query by selector
js// jQuery $('selector'); // Native document.querySelectorAll('selector');1.1 Query by class
js// jQuery $('.class'); // Native document.querySelectorAll('.class'); // or document.getElementsByClassName('class');1.2 Query by id
js// jQuery $('#id'); // Native document.querySelector('#id'); // or document.getElementById('id'); // or window['id']1.3 Query by attribute
js// jQuery $('a[target=_blank]'); // Native document.querySelectorAll('a[target=_blank]');1.4 Query in descendants
js// jQuery $el.find('li'); // Native el.querySelectorAll('li');1.5 Sibling/Previous/Next Elements
All siblings
js// 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
js// jQuery $el.prev(); // Native el.previousElementSibling;Next sibling
js// jQuery $el.next(); // Native el.nextElementSibling;All previous siblings
js// 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// jQuery (optional selector filter) $el.nextAll($filter); // Native (optional filter function) function getNextSiblings(elem, filter) { var sibs = []; var nextElem = elem.parentNode.firstChild; do { if (nextElem.nodeType === 3) continue; // ignore text nodes if (nextElem === elem) continue; // ignore elem of target if (nextElem === elem.nextElementSibling) { if (!filter || filter(elem)) { sibs.push(nextElem); elem = nextElem; } } } while(nextElem = nextElem.nextSibling) return sibs; }
An example of filter function:
function exampleFilter(elem) {
switch (elem.nodeName.toUpperCase()) {
case 'DIV':
return true;
case 'SPAN':
return true;
default:
return false;
}
}1.6 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.
js// 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
js// jQuery $('#my-input').val(); // Native document.querySelector('#my-input').value;Get index of e.currentTarget between
.radiojs// 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()returnscontentDocumentfor this specific iframeIframe contents
js// jQuery $iframe.contents(); // Native iframe.contentDocument;Iframe Query
js// jQuery $iframe.contents().find('.css'); // Native iframe.contentDocument.querySelectorAll('.css');
1.10 Get body
js// jQuery $('body'); // Native document.body;1.11 Attribute getter and setter
Get an attribute
js// jQuery $el.attr('foo'); // Native el.getAttribute('foo');Set an attribute
js// jQuery $el.attr('foo', 'bar'); // Native el.setAttribute('foo', 'bar');Get a
data-attributejs// 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)
js// 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); }); }
CSS & Style
2.1 CSS
Get style
js// 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
js// jQuery $el.css({ color: '#f01' }); // Native el.style.color = '#f01';Get/Set Styles
js// jQuery $el.css({ color: '#f01', 'border-color': '#f02' }) // Native Object.assign(el.style, { color: '#f01', borderColor: '#f02' })Add class
js// jQuery $el.addClass(className); // Native el.classList.add(className);Remove class
js// jQuery $el.removeClass(className); // Native el.classList.remove(className);has class
js// jQuery $el.hasClass(className); // Native el.classList.contains(className);Toggle class
js// 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
js// window height $(window).height(); // without scrollbar, behaves like jQuery window.document.documentElement.clientHeight; // with scrollbar window.innerHeight;Document height
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 );Element height
js// 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.
js// jQuery $el.position(); // Native { left: el.offsetLeft, top: el.offsetTop }Offset
Get the current coordinates of the element relative to the document.
js// 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.
js// jQuery $(window).scrollTop(); // Native (document.documentElement && document.documentElement.scrollTop) || document.body.scrollTop;
DOM Manipulation
3.1 Remove
Remove the element from the DOM.
js// jQuery $el.remove(); // Native el.parentNode.removeChild(el);3.2 Text
Get text
Get the combined text contents of the element including their descendants,
js// jQuery $el.text(); // Native el.textContent;Set text
Set the content of the element to the specified text.
js// jQuery $el.text(string); // Native el.textContent = string;
3.3 HTML
Get HTML
js// jQuery $el.html(); // Native el.innerHTML;Set HTML
js// jQuery $el.html(htmlString); // Native el.innerHTML = htmlString;
3.4 Append
Append child element after the last child of parent element
js// jQuery: unified syntax for DOMString and Node objects $parent.append(newEl | 'Hello World'); // Native: different syntax parent.insertAdjacentHTML('beforeend', 'Hello World'); parent.appendChild(newEl); // Native (ES6-way): unified syntax parent.append(newEl | 'Hello World');3.5 Prepend
js// jQuery: unified syntax for DOMString and Node objects $parent.prepend(newEl | 'Hello World'); // Native: different syntax parent.insertAdjacentHTML('afterbegin', 'Hello World'); parent.insertBefore(newEl, parent.firstChild); // Native (ES6-way): unified syntax parent.prepend(newEl | 'Hello World');3.6 insertBefore
Insert a new node before the selected elements
js// jQuery $newEl.insertBefore(selector); // Native (HTML string) el.insertAdjacentHTML('beforebegin', 'Hello World'); // Native (Element) const el = document.querySelector(selector); if (el.parentNode) { el.parentNode.insertBefore(newEl, el); }3.7 insertAfter
Insert a new node after the selected elements
js// jQuery $newEl.insertAfter(selector); // Native (HTML string) el.insertAdjacentHTML('afterend', 'Hello World'); // Native (Element) const el = document.querySelector(selector); if (el.parentNode) { el.parentNode.insertBefore(newEl, el.nextSibling); }3.8 is
Return
trueif it matches the query selectorjs// jQuery - Notice `is` also works with a function, an existing jQuery object or a DOM element, which are not of concern here $el.is(selector); // Native el.matches(selector);3.9 clone
Create a deep copy of an element: it copies the matched element as well as all of its descendant elements and text nodes.
js// jQuery. Sets parameter as `true` to indicate that event handlers should be copied along with the element. $el.clone(); // Native el.cloneNode();3.10 empty
Remove all child nodes
js// jQuery $el.empty(); // Native el.innerHTML = null;3.11 wrap
Wrap an HTML structure around each element
js// jQuery $('.inner').wrap(''); // Native Array.from(document.querySelectorAll('.inner')).forEach((el) => { const wrapper = document.createElement('div'); wrapper.className = 'wrapper'; el.parentNode.insertBefore(wrapper, el); wrapper.appendChild(el); });3.12 unwrap
Remove the parents of the set of matched elements from the DOM
js// jQuery $('.inner').unwrap(); // Native Array.from(document.querySelectorAll('.inner')).forEach((el) => { let elParentNode = el.parentNode; if(elParentNode !== document.body) { elParentNode.parentNode.insertBefore(el, elParentNode); elParentNode.parentNode.removeChild(elParentNode); } });3.13 replaceWith
Replace each element in the set of matched elements with the provided new content
js// jQuery $('.inner').replaceWith(''); // Native (alternative) - latest, Edge17+ Array.from(document.querySelectorAll('.inner')).forEach((el) => { const outer = document.createElement('div'); outer.className = 'outer'; el.replaceWith(outer); }); // Native Array.from(document.querySelectorAll('.inner')).forEach((el) => { const outer = document.createElement('div'); outer.className = 'outer'; el.parentNode.replaceChild(outer, el); });3.14 simple parse
Parse a string into HTML/SVG/XML
js// jQuery $(`<ol> <li>a</li> <li>b</li> </ol> <ol> <li>c</li> <li>d</li> </ol>`); // Native range = document.createRange(); parse = range.createContextualFragment.bind(range); parse(`<ol> <li>a</li> <li>b</li> </ol> <ol> <li>c</li> <li>d</li> </ol>`);
Ajax
Fetch API is the new standard to replace XMLHttpRequest to do ajax. It works on Chrome and Firefox, you can use polyfills to make it work on legacy browsers.
Try github/fetch on IE9+ or fetch-ie8 on IE8+, fetch-jsonp to make JSONP requests.
4.1 Load data from the server and place the returned HTML into the matched element.
js// jQuery $(selector).load(url, completeCallback) // Native fetch(url).then(data => data.text()).then(data => { document.querySelector(selector).innerHTML = data }).then(completeCallback)
Events
For a complete replacement with namespace and delegation, refer to https://github.com/oneuijs/oui-dom-events
5.0 Document ready by
DOMContentLoadedjs// jQuery $(document).ready(eventHandler); // Native // Check if the DOMContentLoaded has already been completed if (document.readyState !== 'loading') { eventHandler(); } else { document.addEventListener('DOMContentLoaded', eventHandler); } // Native // Example 2 - Ternary Operator - Async // Check if the DOMContentLoaded has already been completed (async function() { (document.readyState !== 'loading') ? eventHandler() : document.addEventListener('DOMContentLoaded', function() { eventHandler(); // EventHandler }); })(); // Native // Example 3 - Ternary Operator - Non Async // Check if the DOMContentLoaded has already been completed (function() { (document.readyState !== 'loading') ? eventHandler() : document.addEventListener('DOMContentLoaded', function() { eventHandler(); // EventHandler }); })();5.1 Bind an event with on
js// jQuery $el.on(eventName, eventHandler); // Native el.addEventListener(eventName, eventHandler);5.2 Unbind an event with off
js// jQuery $el.off(eventName, eventHandler); // Native el.removeEventListener(eventName, eventHandler);5.3 Trigger
js// jQuery $(el).trigger('custom-event', {key1: 'data'}); // Native if (window.CustomEvent) { const event = new CustomEvent('custom-event', {detail: {key1: 'data'}}); } else { const event = document.createEvent('CustomEvent'); event.initCustomEvent('custom-event', true, true, {key1: 'data'}); } el.dispatchEvent(event);
Utilities
Most of jQuery utilities are also found in the native API. Other advanced functions could be chosen from better utilities libraries, focusing on consistency and performance. Lodash is a recommended replacement.
6.1 Basic utilities
- isArray
Determine whether the argument is an array.
js// jQuery $.isArray(array); // Native Array.isArray(array);- isWindow
Determine whether the argument is a window.
js// jQuery $.isWindow(obj); // Native function isWindow(obj) { return obj !== null && obj !== undefined && obj === obj.window; }- inArray
Search for a specified value within an array and return its index (or -1 if not found).
js// jQuery $.inArray(item, array); // Native array.indexOf(item) > -1; // ES6-way array.includes(item);- isNumeric
Determine if the argument passed is numerical.
Usetypeofto decide the type or thetypeexample for better accuracy.js// jQuery $.isNumeric(item); // Native function isNumeric(n) { return !isNaN(parseFloat(n)) && isFinite(n); }- isFunction
Determine if the argument passed is a JavaScript function object.
js// jQuery $.isFunction(item); // Native function isFunction(item) { if (typeof item === 'function') { return true; } var type = Object.prototype.toString.call(item); return type === '[object Function]' || type === '[object GeneratorFunction]'; }- isEmptyObject
Check to see if an object is empty (contains no enumerable properties).
js// jQuery $.isEmptyObject(obj); // Native function isEmptyObject(obj) { return Object.keys(obj).length === 0; }- isPlainObject
Check to see if an object is a plain object (created using “{}” or “new Object”).
js// jQuery $.isPlainObject(obj); // Native function isPlainObject(obj) { if (typeof (obj) !== 'object' || obj.nodeType || obj !== null && obj !== undefined && obj === obj.window) { return false; } if (obj.constructor && !Object.prototype.hasOwnProperty.call(obj.constructor.prototype, 'isPrototypeOf')) { return false; } return true; }- extend
Merge the contents of two or more objects together into a new object, without modifying either argument.
object.assign is part of ES6 API, and you could also use a polyfill.js// jQuery $.extend({}, object1, object2); // Native Object.assign({}, object1, object2);- trim
Remove the white-space from the beginning and end of a string.
js// jQuery $.trim(string); // Native string.trim();- map
Translate all items in an array or object to new array of items.
js// jQuery $.map(array, (value, index) => { }); // Native array.map((value, index) => { });- each
A generic iterator function, which can be used to seamlessly iterate over both objects and arrays.
js// jQuery $.each(array, (index, value) => { }); // Native array.forEach((value, index) => { });- grep
Finds the elements of an array which satisfy a filter function.
js// jQuery $.grep(array, (value, index) => { }); // Native array.filter((value, index) => { });- type
Determine the internal JavaScript [Class] of an object.
js// jQuery $.type(obj); // Native function type(item) { const reTypeOf = /(?:^\[object\s(.*?)\]$)/; return Object.prototype.toString.call(item) .replace(reTypeOf, '$1') .toLowerCase(); }- merge
Merge the contents of two arrays together into the first array.
js// jQuery, doesn't remove duplicate items $.merge(array1, array2); // Native, doesn't remove duplicate items function merge(...args) { return [].concat(...args) } // ES6-way, doesn't remove duplicate items array1 = [...array1, ...array2] // Set version, does remove duplicate items function merge(...args) { return Array.from(new Set([].concat(...args))) }- now
Return a number representing the current time.
js// jQuery $.now(); // Native Date.now();- proxy
Takes a function and returns a new one that will always have a particular context.
js// jQuery $.proxy(fn, context); // Native fn.bind(context);Convert an array-like object into a true JavaScript array.
js// jQuery $.makeArray(arrayLike); // Native Array.prototype.slice.call(arrayLike); // ES6-way: Array.from() method Array.from(arrayLike); // ES6-way: spread operator [...arrayLike];6.2 Contains
Check to see if a DOM element is a descendant of another DOM element.
js// jQuery $.contains(el, child); // Native el !== child && el.contains(child);6.3 Globaleval
Execute some JavaScript code globally.
js// jQuery $.globaleval(code); // Native function Globaleval(code) { const script = document.createElement('script'); script.text = code; document.head.appendChild(script).parentNode.removeChild(script); } // Use eval, but context of eval is current, context of $.Globaleval is global. eval(code);6.4 parse
- parseHTML
Parses a string into an array of DOM nodes.
js// jQuery $.parseHTML(htmlString); // Native function parseHTML(string) { const context = document.implementation.createHTMLDocument(); // Set the base href for the created document so any parsed elements with URLs // are based on the document's URL const base = context.createElement('base'); base.href = document.location.href; context.head.appendChild(base); context.body.innerHTML = string; return context.body.children; }6.5 exists
exists
Check if an element exists in the DOM
js// jQuery if ($('selector').length) { // exists } // Native var element = document.getElementById('elementId'); if (typeof(element) != 'undefined' && element != null) { // exists }
Promises
A promise represents the eventual result of an asynchronous operation. jQuery has its own way to handle promises. Native JavaScript implements a thin and minimal API to handle promises according to the Promises/A+ specification.
7.1 done, fail, always
doneis called when promise is resolved,failis called when promise is rejected,alwaysis called when promise is either resolved or rejected.js// jQuery $promise.done(doneCallback).fail(failCallback).always(alwaysCallback) // Native promise.then(doneCallback, failCallback).then(alwaysCallback, alwaysCallback)7.2 when
whenis used to handle multiple promises. It will resolve when all promises are resolved, and reject if either one is rejected.js// jQuery $.when($promise1, $promise2).done((promise1Result, promise2Result) => { }); // Native Promise.all([$promise1, $promise2]).then(([promise1Result, promise2Result]) => {});7.3 Deferred
Deferred is a way to create promises.
js// jQuery function asyncFunc() { const defer = new $.Deferred(); setTimeout(() => { if(true) { defer.resolve('some_value_computed_asynchronously'); } else { defer.reject('failed'); } }, 1000); return defer.promise(); } // Native function asyncFunc() { return new Promise((resolve, reject) => { setTimeout(() => { if (true) { resolve('some_value_computed_asynchronously'); } else { reject('failed'); } }, 1000); }); } // Deferred way function defer() { const deferred = {}; const promise = new Promise((resolve, reject) => { deferred.resolve = resolve; deferred.reject = reject; }); deferred.promise = () => { return promise; }; return deferred; } function asyncFunc() { const defer = defer(); setTimeout(() => { if(true) { defer.resolve('some_value_computed_asynchronously'); } else { defer.reject('failed'); } }, 1000); return defer.promise(); }
Animation
8.1 Show & Hide
js// jQuery $el.show(); $el.hide(); // Native // More detail about show method, please refer to https://github.com/oneuijs/oui-dom-utils/blob/master/src/index.js#L363 el.style.display = ''|'inline'|'inline-block'|'inline-table'|'block'; el.style.display = 'none';8.2 Toggle
Display or hide the element.
js// jQuery $el.toggle(); // Native if (el.ownerDocument.defaultView.getComputedStyle(el, null).display === 'none') { el.style.display = ''|'inline'|'inline-block'|'inline-table'|'block'; } else { el.style.display = 'none'; }8.3 FadeIn & FadeOut
js// jQuery $el.fadeIn(3000); $el.fadeOut(3000); // Native fadeOut function fadeOut(el, ms) { if (ms) { el.style.transition = `opacity ${ms} ms`; el.addEventListener( 'transitionend', function(event) { el.style.display = 'none'; }, false ); } el.style.opacity = '0'; } // Native fadeIn function fadeIn(elem, ms) { elem.style.opacity = 0; if (ms) { let opacity = 0; const timer = setInterval(function() { opacity += 50 / ms; if (opacity >= 1) { clearInterval(timer); opacity = 1; } elem.style.opacity = opacity; }, 50); } else { elem.style.opacity = 1; } }8.4 FadeTo
Adjust the opacity of the element.
js// jQuery $el.fadeTo('slow',0.15); // Native el.style.transition = 'opacity 3s'; // assume 'slow' equals 3 seconds el.style.opacity = '0.15';8.5 FadeToggle
Display or hide the element by animating their opacity.
js// jQuery $el.fadeToggle(); // Native el.style.transition = 'opacity 3s'; const { opacity } = el.ownerDocument.defaultView.getComputedStyle(el, null); if (opacity === '1') { el.style.opacity = '0'; } else { el.style.opacity = '1'; }8.6 SlideUp & SlideDown
js// jQuery $el.slideUp(); $el.slideDown(); // Native const originHeight = '100px'; el.style.transition = 'height 3s'; // slideUp el.style.height = '0px'; // slideDown el.style.height = originHeight;8.7 SlideToggle
Display or hide the element with a sliding motion.
js// jQuery $el.slideToggle(); // Native const originHeight = '100px'; el.style.transition = 'height 3s'; const { height } = el.ownerDocument.defaultView.getComputedStyle(el, null); if (parseInt(height, 10) === 0) { el.style.height = originHeight; } else { el.style.height = '0px'; }8.8 Animate
Perform a custom animation of a set of CSS properties.
js// jQuery $el.animate({ params }, speed); // Native el.style.transition = 'all ' + speed; Object.keys(params).forEach((key) => { el.style[key] = params[key]; });
Alternatives
- You Might Not Need jQuery - Examples of how to do common event, element, ajax etc with plain javascript.
- npm-dom and webmodules - Organizations you can find individual DOM modules on NPM
Browser Support
![]() |
![]() |
![]() |
![]() |
![]() |
|---|---|---|---|---|
| Latest ✔ | Latest ✔ | 10+ ✔ | Latest ✔ | 6.1+ ✔ |
License
MIT
File: README.ko-KR.md
You (Might) Don't Need jQuery
오늘날 프론트엔드 개발 환경은 급격히 진화하고 있고, 모던 브라우저들은 이미 충분히 많은 DOM/BOM API들을 구현했습니다. 우리는 jQuery를 DOM 처리나 이벤트를 위해 처음부터 배울 필요가 없습니다. React, Angular, Vue같은 프론트엔드 라이브러리들이 주도권을 차지하는 동안 DOM을 바로 처리하는 것은 안티패턴이 되었고, jQuery의 중요성은 줄어들었습니다. 이 프로젝트는 대부분의 jQuery 메소드의 대안을 IE 10 이상을 지원하는 네이티브 구현으로 소개합니다.
노트: jQuery는 여전히 훌륭한 라이브러리이며 많은 유즈 케이스를 갖고 있습니다. 원하지 않으신다면 마이그레이트하지 않으셔도됩니다.
목차
번역
- 한국어
- 正體中文
- 简体中文
- Bahasa Melayu
- Bahasa Indonesia
- Português(PT-BR)
- Tiếng Việt Nam
- Español
- Русский
- Кыргызча
- Türkçe
- Italiano
- Français
- 日本語
- Polski
Query Selector
평범한 class, id, attribute같은 selector는 document.querySelector나 document.querySelectorAll으로 대체할 수 있습니다.
document.querySelector는 처음 매칭된 엘리먼트를 반환합니다.document.querySelectorAll는 모든 매칭된 엘리먼트를 NodeList로 반환합니다.Array.prototype.slice.call(document.querySelectorAll(selector));을 사용해서 Array로 변환할 수 있습니다.- 만약 매칭된 엘리멘트가 없으면 jQuery와
document.querySelectorAll는[]를 반환하지만document.querySelector는null을 반환합니다.
안내:
document.querySelector와document.querySelectorAll는 꽤 느립니다,getElementById나document.getElementsByClassName,document.getElementsByTagName를 사용하면 퍼포먼스가 향상을 기대할 수 있습니다.
1.0 selector로 찾기
js// jQuery $('selector'); // Native document.querySelectorAll('selector');1.1 class로 찾기
js// jQuery $('.class'); // Native document.querySelectorAll('.class'); // 또는 document.getElementsByClassName('class');1.2 id로 찾기
js// jQuery $('#id'); // Native document.querySelector('#id'); // 또는 document.getElementById('id'); // 또는 window['id']1.3 속성(attribute)으로 찾기
js// jQuery $('a[target=_blank]'); // Native document.querySelectorAll('a[target=_blank]');1.4 자식에서 찾기
js// jQuery $el.find('li'); // Native el.querySelectorAll('li');1.5 형제/이전/다음 엘리먼트 찾기
형제 엘리먼트
js// 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 );이전 엘리먼트
js// jQuery $el.prev(); // Native el.previousElementSibling;다음 엘리먼트
js// jQuery $el.next(); // Native el.nextElementSibling;모든 이전 형제 엘리먼트
js// jQuery (선택적 필터 셀렉터) $el.prevAll($filter); // Native (선택적 필터 함수) function getPreviousSiblings(elem, filter) { var sibs = []; while (elem = elem.previousSibling) { if (elem.nodeType === 3) continue; // 텍스트 노트 무시 if (!filter || filter(elem)) sibs.push(elem); } return sibs; }모든 다음 형제 엘리먼트
js// jQuery (선택적 셀렉터 필터) $el.nextAll($filter); // Native (선택적 필터 함수) function getNextSiblings(elem, filter) { var sibs = []; var nextElem = elem.parentNode.firstChild; do { if (nextElem.nodeType === 3) continue; // 텍스트 노드 무시 if (nextElem === elem) continue; // 대상 elem 무시 if (nextElem === elem.nextElementSibling) { if (!filter || filter(elem)) { sibs.push(nextElem); elem = nextElem; } } } while(nextElem = nextElem.nextSibling) return sibs; }
필터 함수 예제:
function exampleFilter(elem) {
switch (elem.nodeName.toUpperCase()) {
case 'DIV':
return true;
case 'SPAN':
return true;
default:
return false;
}
}1.6 Closest
현재 엘리먼트부터 document로 이동하면서 주어진 셀렉터와 일치하는 가장 가까운 엘리먼트를 반환합니다.
js// jQuery $el.closest(selector); // Native - 최신 브라우저만, 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
주어진 셀렉터에 매칭되는 엘리먼트를 찾기까지 부모 태그들을 위로 올라가며 탐색하여 저장해두었다가 DOM 노드 또는 jQuery object로 반환합니다.
js// 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
js// jQuery $('#my-input').val(); // Native document.querySelector('#my-input').value;e.currentTarget이 몇 번째
.radio인지 구하기js// jQuery $(e.currentTarget).index('.radio'); // Native Array.from(document.querySelectorAll('.radio')).indexOf(e.currentTarget); 또는 Array.prototype.indexOf.call(document.querySelectorAll('.radio'), e.currentTarget);
1.9 Iframe Contents
$('iframe').contents()는 iframe에 한정해서contentDocument를 반환합니다.Iframe contents
js// jQuery $iframe.contents(); // Native iframe.contentDocument;Iframe에서 찾기
js// jQuery $iframe.contents().find('.css'); // Native iframe.contentDocument.querySelectorAll('.css');
1.10 body 얻기
js// jQuery $('body'); // Native document.body;1.11 속성 얻기 및 설정
속성 얻기
js// jQuery $el.attr('foo'); // Native el.getAttribute('foo');속성 설정하기
js// jQuery, DOM 변형 없이 메모리에서 작동됩니다. $el.attr('foo', 'bar'); // Native el.setAttribute('foo', 'bar');data-속성 얻기js// jQuery $el.data('foo'); // Native (`getAttribute` 사용) el.getAttribute('data-foo'); // Native (IE 11 이상의 지원만 필요하다면 `dataset`을 사용) el.dataset['foo'];
1.12 문자열을 포함하는 셀렉터(대소문자 구분)
js// 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); }); }
CSS & Style
2.1 CSS
style값 얻기
js// jQuery $el.css("color"); // Native // NOTE: 알려진 버그로, style값이 'auto'이면 'auto'를 반환합니다. const win = el.ownerDocument.defaultView; // null은 가상 스타일은 반환하지 않음을 의미합니다. win.getComputedStyle(el, null).color;style값 설정하기
js// jQuery $el.css({ color: '#f01' }); // Native el.style.color = '#f01';Style값들을 동시에 얻거나 설정하기
만약 한번에 여러 style값을 바꾸고 싶다면 oui-dom-utils 패키지의 setStyles를 사용해보세요.
class 추가하기
js// jQuery $el.addClass(className); // Native el.classList.add(className);class 제거하기
js// jQuery $el.removeClass(className); // Native el.classList.remove(className);class를 포함하고 있는지 검사하기
js// jQuery $el.hasClass(className); // Native el.classList.contains(className);class 토글하기
js// jQuery $el.toggleClass(className); // Native el.classList.toggle(className);
2.2 폭과 높이
폭과 높이는 이론상 동일합니다. 높이로 예를 들겠습니다.
Window의 높이
js// window 높이 $(window).height(); // jQuery처럼 스크롤바를 제외하기 window.document.documentElement.clientHeight; // 스크롤바 포함 window.innerHeight;문서 높이
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 );Element 높이
js// 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; } // 정수로 정확하게(`border-box`일 때 이 값은 `height - border`이고, `content-box`일 때, 이 값은 `height + padding`) el.clientHeight; // 실수로 정확하게(`border-box`일 때 이 값은 `height`이고, `content-box`일 때, 이 값은 `height + padding + border`) el.getBoundingClientRect().height;
2.3 Position & Offset
Position
오프셋 부모를 기준으로 엘리먼트의 현재 위치를 얻습니다.
js// jQuery $el.position(); // Native { left: el.offsetLeft, top: el.offsetTop }Offset
다큐먼트를 기준으로 엘리먼트의 현재 위치를 얻습니다.
js// 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
엘리먼트에대한 스크롤바의 현재 수직 위치를 얻습니다.
js// jQuery $(window).scrollTop(); // Native (document.documentElement && document.documentElement.scrollTop) || document.body.scrollTop;
DOM 조작
3.1 제거
DOM으로부터 엘리먼트를 제거합니다.
js// jQuery $el.remove(); // Native el.parentNode.removeChild(el);3.2 Text
text 가져오기
자손을 포함하는 엘리먼트의 결합된 텍스트 컨텐츠를 얻습니다.
js// jQuery $el.text(); // Native el.textContent;text 설정하기
엘리먼트의 컨텐츠를 지정한 텍스트로 설정합니다.
js// jQuery $el.text(string); // Native el.textContent = string;
3.3 HTML
HTML 가져오기
js// jQuery $el.html(); // Native el.innerHTML;HTML 설정하기
js// jQuery $el.html(htmlString); // Native el.innerHTML = htmlString;
3.4 해당 엘리먼트의 자식들 뒤에 넣기(Append)
부모 엘리먼트의 마지막 자식 다음으로 엘리먼트를 추가합니다.
js// jQuery: DOMString과 Node 객체를 위한 통합된 구문 $parent.append(newEl | 'Hello World'); // Native: 다른 구문 parent.insertAdjacentHTML('beforeend', 'Hello World'); parent.appendChild(newEl); // Native (ES6 방식): 통합된 구문 parent.append(newEl | 'Hello World');3.5 해당 엘리먼트의 자식들 앞에 넣기(Prepend)
js// jQuery: DOMString과 Node 객체를 위한 통합된 구문 $parent.prepend(newEl | 'Hello World'); // Native: 다른 구문 parent.insertAdjacentHTML('afterbegin', 'Hello World'); parent.insertBefore(newEl, parent.firstChild); // Native (ES6 방식): 통합된 구문 parent.prepend(newEl | 'Hello World');3.6 해당 엘리먼트 앞에 넣기(insertBefore)
새 노드를 선택한 엘리먼트 앞에 넣습니다.
js// jQuery $newEl.insertBefore(selector); // Native (HTML 문자열) el.insertAdjacentHTML('beforebegin', 'Hello World'); // Native (엘리먼트) const el = document.querySelector(selector); if (el.parentNode) { el.parentNode.insertBefore(newEl, el); }3.7 해당 엘리먼트 뒤에 넣기(insertAfter)
새 노드를 선택한 엘리먼트 뒤에 넣습니다.
js// jQuery $newEl.insertAfter(selector); // Native (HTML 문자열) el.insertAdjacentHTML('afterend', 'Hello World'); // Native (엘리먼트) onst el = document.querySelector(selector); if (el.parentNode) { el.parentNode.insertBefore(newEl, el.nextSibling); }3.8 is
query selector와 일치하면
true를 반환합니다.js// jQuery - `is`는 함수, 존재하는 jQuery 객체 또는 여기에서 언급하지 않은 DOM 엘리먼트와도 동작함을 알립니다. $el.is(selector); // Native el.matches(selector);3.9 clone
엘리먼트의 깊은 복사본을 생성합니다. 일치한 엘리먼트를 포함해 그 자손 노드와 텍스트 노드를 모두 복사합니다.
js// jQuery. 이벤트 핸들러가 엘리먼트와 함께 복사되어야함을 알리려면 파라미터를 `true`로 설정하세요. $el.clone(); // Native el.cloneNode();3.10 empty
모든 자식 노드를 제거합니다.
js// jQuery $el.empty(); // Native el.innerHTML = null;3.11 wrap
각각의 엘리먼트를 주어진 HTML 구조로 감쌉니다.
js// jQuery $('.inner').wrap(''); // Native Array.from(document.querySelectorAll('.inner')).forEach((el) => { const wrapper = document.createElement('div'); wrapper.className = 'wrapper'; el.parentNode.insertBefore(wrapper, el); wrapper.appendChild(el); });3.12 unwrap
DOM에서 해당 엘리먼트를 감싸고 있는 부모 요소를 없앱니다.
js// jQuery $('.inner').unwrap(); // Native Array.from(document.querySelectorAll('.inner')).forEach((el) => { let elParentNode = el.parentNode; if (elParentNode !== document.body) { elParentNode.parentNode.insertBefore(el, elParentNode); elParentNode.parentNode.removeChild(elParentNode); } });3.13 replaceWith
각각의 엘리먼트를 주어진 새 엘리먼트로 교체합니다.
js// jQuery $('.inner').replaceWith(''); // Native (대안) - 최신, Edge17+ Array.from(document.querySelectorAll('.inner')).forEach((el) => { const outer = document.createElement('div'); outer.className = 'outer'; el.replaceWith(outer); }); // Native Array.from(document.querySelectorAll('.inner')).forEach((el) => { const outer = document.createElement('div'); outer.className = 'outer'; el.parentNode.replaceChild(outer, el); });3.14 간단한 파싱
문자열을 HTML/SVG/XML 로 파싱합니다.
js// jQuery $(`<ol> <li>a</li> <li>b</li> </ol> <ol> <li>c</li> <li>d</li> </ol>`); // Native range = document.createRange(); parse = range.createContextualFragment.bind(range); parse(`<ol> <li>a</li> <li>b</li> </ol> <ol> <li>c</li> <li>d</li> </ol>`);
Ajax
Fetch API 는 XMLHttpRequest를 ajax로 대체하는 새로운 표준 입니다. Chrome과 Firefox에서 작동하며, polyfill을 이용해서 구형 브라우저에서 작동되도록 만들 수도 있습니다.
IE9 이상에서 지원하는 github/fetch 혹은 IE8 이상에서 지원하는 fetch-ie8, JSONP 요청을 만드는 fetch-jsonp를 이용해보세요.
4.1 서버로부터 HTML data를 불러와서 매칭된 엘리먼트에 배치.
js// jQuery $(selector).load(url, completeCallback) // Native fetch(url).then(data => data.text()).then(data => { document.querySelector(selector).innerHTML = data }).then(completeCallback)
이벤트
namespace와 delegation을 포함해서 완전히 갈아 엎길 원하시면 https://github.com/oneuijs/oui-dom-events 를 고려해보세요.
5.0
DOMContentLoaded가 되어 문서가 사용 가능한지js// jQuery $(document).ready(eventHandler); // Native // DOMContentLoaded가 이미 완료되었는지를 확인 if (document.readyState !== 'loading') { eventHandler(); } else { document.addEventListener('DOMContentLoaded', eventHandler); }5.1 이벤트 Bind 걸기
js// jQuery $el.on(eventName, eventHandler); // Native el.addEventListener(eventName, eventHandler);5.2 이벤트 Bind 풀기
js// jQuery $el.off(eventName, eventHandler); // Native el.removeEventListener(eventName, eventHandler);5.3 이벤트 발생시키기(Trigger)
js// jQuery $(el).trigger('custom-event', {key1: 'data'}); // Native if (window.CustomEvent) { const event = new CustomEvent('custom-event', {detail: {key1: 'data'}}); } else { const event = document.createEvent('CustomEvent'); event.initCustomEvent('custom-event', true, true, {key1: 'data'}); } el.dispatchEvent(event);
유틸리티
대부분의 jQuery 유틸은 네이티브 API에서도 찾을 수 있습니다. 다른 향상된 기능들은 지속성과 성능에 중점을 둔 더 나은 유틸 라이브러리로부터 선택할 수 있습니다. 권장하는 대안은 Lodash입니다.
6.1 기본 유틸리티
- isArray
주어진 인자가 배열인지 검사합니다.
js// jQuery $.isArray(array); // Native Array.isArray(array);- isWindow
주어진 인자가 window 객체인지 검사합니다.
js// jQuery $.isWindow(obj); // Native function isWindow(obj) { return obj !== null && obj !== undefined && obj === obj.window; }- inArray
배열에서 해당 값이 있는지 검색하고 해당 값의 순번을 반환합니다. (검색 결과가 없을 경우 -1을 반환)
js// jQuery $.inArray(item, array); // Native array.indexOf(item) > -1; // ES6 방식 array.includes(item);- isNumeric
주어진 인자가 숫자인지 검사합니다.
검사에typeof를 사용합니다. 필요하면 라이브러리를 사용하세요. 가끔typeof는 정확하지 않습니다.js// jQuery $.isNumeric(item); // Native function isNumeric(n) { return !isNaN(parseFloat(n)) && isFinite(n); }- isFunction
주어진 인자가 JavaScript 함수 객체인지 검사합니다.
js// jQuery $.isFunction(item); // Native function isFunction(item) { if (typeof item === 'function') { return true; } var type = Object.prototype.toString(item); return type === '[object Function]' || type === '[object GeneratorFunction]'; }- isEmptyObject
객체가 비어있는지 검사합니다. Check to see if an object is empty (열거할 수 있는 프로퍼티가 없는지 검사).
js// jQuery $.isEmptyObject(obj); // Native function isEmptyObject(obj) { return Object.keys(obj).length === 0; }- isPlainObject
주어진 객체가 평범한 객체인지 검사합니다. (“{}”이나 “new Object”으로 생성되었는지 검사)
js// jQuery $.isPlainObject(obj); // Native function isPlainObject(obj) { if (typeof (obj) !== 'object' || obj.nodeType || obj !== null && obj !== undefined && obj === obj.window) { return false; } if (obj.constructor && !Object.prototype.hasOwnProperty.call(obj.constructor.prototype, 'isPrototypeOf')) { return false; } return true; }- extend
두 개 이상의 객체를 첫 번째 객체로 합칩니다.
object.assign 은 ES6 API입니다. polyfill 을 사용할 수 있습니다.js// jQuery $.extend({}, defaultOpts, opts); // Native Object.assign({}, defaultOpts, opts);- trim
문자열 앞뒤에 붙은 공백문자를 제거합니다.
js// jQuery $.trim(string); // Native string.trim();- map
배열이나 객체 내의 모든 요소를 새 배열에 변환하여 저장합니다.
js// jQuery $.map(array, (value, index) => { }); // Native array.map((value, index) => { });- each
객체나 함수 모두에 매끄럽게 사용할 수 있는 포괄적인 용도의 반복 함수입니다.
js// jQuery $.each(array, (index, value) => { }); // Native array.forEach((value, index) => { });- grep
배열에서 필터 함수를 만족하는 엘리먼트를 찾습니다.
js// jQuery $.grep(array, (value, index) => { }); // Native array.filter((value, index) => { });- type
객체의 JavaScript 내부 [[Class]]를 검사합니다.
js// jQuery $.type(obj); // Native function type(item) { const reTypeOf = /(?:^\[object\s(.*?)\]$)/; return Object.prototype.toString.call(item) .replace(reTypeOf, '$1') .toLowerCase(); }- merge
두 배열을 첫 번째 배열로 합칩니다.
js// jQuery, 중복된 항목을 제거하지 않습니다 $.merge(array1, array2); // Native, 중복된 항목을 제거하지 않습니다 function merge(...args) { return [].concat(...args) } // ES6 방식, 중복된 항목을 제거하지 않습니다 array1 = [...array1, ...array2] // Set 버전, 중복된 항목을 제거합니다 function merge(...args) { return Array.from(new Set([].concat(...args))) }- now
현재 시간을 숫자로 반환합니다.
js// jQuery $.now(); // Native Date.now();- proxy
함수를 받아서 언제나 특정 context를 갖는 새 함수를 반환합니다.
js// jQuery $.proxy(fn, context); // Native fn.bind(context);array-like 한 객체를 진짜 JavaScript 배열로 변환합니다.
js// jQuery $.makeArray(arrayLike); // Native Array.prototype.slice.call(arrayLike); // ES6 방식: Array.from() 메소드 Array.from(arrayLike); // ES6 방식: spread 연산자 [...arrayLike];6.2 Contains
주어진 엘리먼트가 주어진 또 다른 엘리먼트를 자손으로 포함하는지 검사합니다.
js// jQuery $.contains(el, child); // Native el !== child && el.contains(child);6.3 Globaleval
JavaScript 코드를 전역적으로 실행합니다.
js// jQuery $.globaleval(code); // Native function Globaleval(code) { const script = document.createElement('script'); script.text = code; document.head.appendChild(script).parentNode.removeChild(script); } // eval 함수를 쓸 수도 있습니다. 하지만 $.Globaleval 의 context가 전역인 데 반해 eval 함수의 context 는 실행 영역입니다. eval(code);6.4 parse
- parseHTML
문자열을 DOM 노드의 배열로 변환합니다.
js// jQuery $.parseHTML(htmlString); // Native function parseHTML(string) { const context = document.implementation.createHTMLDocument(); // 생성된 도큐먼트를 위해 base href를 지정해서 URL이 있는 엘리먼트들은 도큐먼트 기준으로 처리됩니다. const base = context.createElement('base'); base.href = document.location.href; context.head.appendChild(base); context.body.innerHTML = string; return context.body.children; }6.5 exists
exists
엘리먼트가 DOM에 존재하는지를 확인합니다
js// jQuery if ($('selector').length) { // 존재함 } // Native var element = document.getElementById('elementId'); if (typeof(element) != 'undefined' && element != null) { // 존재함 }
Promises
Promise는 비동기적인 작업의 결과를 표현합니다. jQuery는 자체적인 promise 처리를 가지고 있습니다. 네이티브 JavaScript엔 Promises/A+ 명세에 맞는 얇고 작은 API를 구현되어 있습니다.
7.1 done, fail, always
done은 promise가 처리되었을 때,fail은 promise가 거절되었을 때,always는 promise가 어떻게 되었건 실행됩니다.js// jQuery $promise.done(doneCallback).fail(failCallback).always(alwaysCallback) // Native promise.then(doneCallback, failCallback).then(alwaysCallback, alwaysCallback)7.2 when
when은 여러 개의 promise들을 처리할 때 사용됩니다. 이것은 모든 promise가 처리되었을 때 resolve하고 하나라도 거절되면 reject합니다.js// jQuery $.when($promise1, $promise2).done((promise1Result, promise2Result) => { }); // Native Promise.all([$promise1, $promise2]).then([promise1Result, promise2Result] => {});7.3 Deferred
Deferred는 promise를 생성하는 방법입니다.
js// jQuery function asyncFunc() { const defer = new $.Deferred(); setTimeout(() => { if(true) { defer.resolve('some_value_computed_asynchronously'); } else { defer.reject('failed'); } }, 1000); return defer.promise(); } // Native function asyncFunc() { return new Promise((resolve, reject) => { setTimeout(() => { if (true) { resolve('some_value_computed_asynchronously'); } else { reject('failed'); } }, 1000); }); } // Deferred way function defer() { const deferred = {}; const promise = new Promise((resolve, reject) => { deferred.resolve = resolve; deferred.reject = reject; }); deferred.promise = () => { return promise; }; return deferred; } function asyncFunc() { const defer = defer(); setTimeout(() => { if (true) { defer.resolve('some_value_computed_asynchronously'); } else { defer.reject('failed'); } }, 1000); return defer.promise(); }
Animation
8.1 Show & Hide
js// jQuery $el.show(); $el.hide(); // Native // show 메소드에 대한 더 자세한 정보를 보고 싶으면 https://github.com/oneuijs/oui-dom-utils/blob/master/src/index.js#L363 를 참고하세요 el.style.display = ''|'inline'|'inline-block'|'inline-table'|'block'; el.style.display = 'none';8.2 Toggle
엘리먼트를 출력하거나 숨깁니다.
js// jQuery $el.toggle(); // Native if (el.ownerDocument.defaultView.getComputedStyle(el, null).display === 'none') { el.style.display = ''|'inline'|'inline-block'|'inline-table'|'block'; } else { el.style.display = 'none'; }8.3 FadeIn & FadeOut
js// jQuery $el.fadeIn(3000); $el.fadeOut(3000); // Native fadeOut function fadeOut(el, ms) { if (ms) { el.style.transition = `opacity ${ms} ms`; el.addEventListener( 'transitionend', function(event) { el.style.display = 'none'; }, false ); } el.style.opacity = '0'; } // Native fadeIn function fadeIn(elem, ms) { elem.style.opacity = 0; if (ms) { let opacity = 0; const timer = setInterval(function() { opacity += 50 / ms; if (opacity >= 1) { clearInterval(timer); opacity = 1; } elem.style.opacity = opacity; }, 50); } else { elem.style.opacity = 1; } }8.4 FadeTo
엘리먼트의 투명도(opacity)를 조정합니다.
js// jQuery $el.fadeTo('slow',0.15); // Native el.style.transition = 'opacity 3s'; // 'slow'가 3초라고 가정합니다. el.style.opacity = '0.15';8.5 FadeToggle
엘리먼트를 투명도를 조절해서 보여주거나 숨깁니다.
js// jQuery $el.fadeToggle(); // Native el.style.transition = 'opacity 3s'; const { opacity } = el.ownerDocument.defaultView.getComputedStyle(el, null); if (opacity === '1') { el.style.opacity = '0'; } else { el.style.opacity = '1'; }8.6 SlideUp & SlideDown
js// jQuery $el.slideUp(); $el.slideDown(); // Native const originHeight = '100px'; el.style.transition = 'height 3s'; // slideUp el.style.height = '0px'; // slideDown el.style.height = originHeight;8.7 SlideToggle
슬라이딩 모션과 함께 엘리먼트를 보이거나 숨깁니다.
js// jQuery $el.slideToggle(); // Native const originHeight = '100px'; el.style.transition = 'height 3s'; const { height } = el.ownerDocument.defaultView.getComputedStyle(el, null); if (parseInt(height, 10) === 0) { el.style.height = originHeight; } else { el.style.height = '0px'; }8.8 Animate
자체적으로 CSS 프로퍼티들을 에니메이션합니다.
js// jQuery $el.animate({ params }, speed); // Native el.style.transition = 'all ' + speed; Object.keys(params).forEach((key) => { el.style[key] = params[key]; });
대안방법
- You Might Not Need jQuery - 일반 자바스크립트로 공통이벤트, 엘리먼트, ajax 등을 다루는 방법 예제.
- npm-dom 과 webmodules - 개별 DOM모듈을 NPM에서 찾을 수 있습니다.
Browser Support
![]() |
![]() |
![]() |
![]() |
![]() |
|---|---|---|---|---|
| Latest ✔ | Latest ✔ | 10+ ✔ | Latest ✔ | 6.1+ ✔ |
License
MIT
File: README.pt-BR.md
You (Might) Don't Need jQuery
Você não precisa de jQuery
Ambientes Frontend evoluem rapidamente nos dias de hoje, navegadores modernos já implementaram uma grande parte das APIs DOM/BOM que são boas o suficiente. Nós não temos que aprender jQuery a partir do zero para manipulação do DOM ou eventos. Nesse meio tempo, graças a bibliotecas frontend como React, Angular e Vue, a manipulação direta do DOM torna-se um anti-padrão, jQuery é menos importante do que nunca. Este projeto resume a maioria das alternativas dos métodos jQuery em implementação nativa, com suporte ao IE 10+.
Tabela de conteúdos
- Translations
- Query Selector
- CSS & Estilo
- Manipulação do DOM
- Ajax
- Eventos
- Utilitários
- Suporte dos Navegadores
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
No lugar de seletores comuns como classe, id ou atributo podemos usar document.querySelector ou document.querySelectorAll para substituição. As diferenças são:
document.querySelectorretorna o primeiro elemento correspondentedocument.querySelectorAllretorna todos os elementos correspondentes como NodeList. Pode ser convertido para Array usando[].slice.call(document.querySelectorAll(selector) || []);- Se não tiver elementos correspondentes, jQuery retornaria
[]considerando que a DOM API irá retornarnull. Preste atenção ao Null Pointer Exception. Você também pode usar||para definir um valor padrão caso nenhum elemento seja encontrado, comodocument.querySelectorAll(selector) || []
Aviso:
document.querySelectoredocument.querySelectorAllsão bastante LENTOS, tente usargetElementById,document.getElementsByClassNameoudocument.getElementsByTagNamese você quer ter uma maior performance.
1.0 Query por seletor
js// jQuery $('selector'); // Nativo document.querySelectorAll('selector');1.1 Query por classe
js// jQuery $('.class'); // Nativo document.querySelectorAll('.class'); // ou document.getElementsByClassName('class');1.2 Query por id
js// jQuery $('#id'); // Nativo document.querySelector('#id'); // ou document.getElementById('id');1.3 Query por atributo
js// jQuery $('a[target=_blank]'); // Nativo document.querySelectorAll('a[target=_blank]');1.4 Find sth.
Busca por nós
js// jQuery $el.find('li'); // Nativo el.querySelectorAll('li');Buscar
bodyjs// jQuery $('body'); // Nativo document.body;Buscar atributos
js// jQuery $el.attr('foo'); // Nativo e.getAttribute('foo');Buscar atributos
data-js// jQuery $el.data('foo'); // Nativo // usando getAttribute el.getAttribute('data-foo'); // você também pode usar `dataset` se você precisar suportar apenas IE 11+ el.dataset['foo'];
1.5 Sibling/Previous/Next Elements
Sibling elements
js// jQuery $el.siblings(); // Nativo [].filter.call(el.parentNode.children, function(child) { return child !== el; });Previous elements
js// jQuery $el.prev(); // Nativo el.previousElementSibling;Next elements
js// jQuery $el.next(); // Nativo el.nextElementSibling;
1.6 Closest
Retorna o primeiro elemento que corresponda ao seletor, partindo do elemento atual para o document.
js// jQuery $el.closest(queryString); // Nativo 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
Obtém os ancestrais de cada elemento no atual conjunto de elementos combinados, mas não inclui o elemento correspondente pelo seletor, nó do DOM, ou objeto jQuery.
js// jQuery $el.parentsUntil(selector, filter); // Nativo 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
js// jQuery $('#my-input').val(); // Nativo document.querySelector('#my-input').value;Obter o índice do e.currentTarget entre
.radiojs// jQuery $(e.currentTarget).index('.radio'); // Nativo [].indexOf.call(document.querySelectAll('.radio'), e.currentTarget);
1.9 Iframe Contents
$('iframe').contents()retornacontentDocumentpara este iframe específicoIframe contents
js// jQuery $iframe.contents(); // Nativo iframe.contentDocument;Iframe Query
js// jQuery $iframe.contents().find('.css'); // Nativo iframe.contentDocument.querySelectorAll('.css');
CSS & Estilo
2.1 CSS
Obter estilo
js// jQuery $el.css("color"); // Nativo // AVISO: Bug conhecido, irá retornar 'auto' se o valor do estilo for 'auto' const win = el.ownerDocument.defaultView; // null significa não retornar estilos win.getComputedStyle(el, null).color;Definir Estilo
js// jQuery $el.css({ color: "#ff0011" }); // Nativo el.style.color = '#ff0011';Get/Set Styles
Observe que se você deseja setar vários estilos de uma vez, você pode optar por setStyles método no pacote oui-dom-utils.
Adicionar classe
js// jQuery $el.addClass(className); // Nativo el.classList.add(className);Remover classe
js// jQuery $el.removeClass(className); // Nativo el.classList.remove(className);Verificar classe
js// jQuery $el.hasClass(className); // Nativo el.classList.contains(className);Toggle class
js// jQuery $el.toggleClass(className); // Nativo el.classList.toggle(className);
2.2 Largura e Altura
widtheheightsão teoricamente idênticos, vamos pegarheightcomo exemplo:Altura da janela
js// window height $(window).height(); // sem scrollbar, se comporta como jQuery window.document.documentElement.clientHeight; // com scrollbar window.innerHeight;Altura do Documento
js// jQuery $(document).height(); // Nativo document.documentElement.scrollHeight;Altura do Elemento
js// jQuery $el.height(); // Nativo function getHeight(el) { const styles = this.getComputedStyles(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; } // preciso para inteiro(quando `border-box`, é `height - border`; quando `content-box`, é `height + padding`) el.clientHeight; // preciso para decimal(quando `border-box`, é `height`; quando `content-box`, é `height + padding + border`) el.getBoundingClientRect().height;
2.3 Position & Offset
Position
js// jQuery $el.position(); // Nativo { left: el.offsetLeft, top: el.offsetTop }Offset
js// jQuery $el.offset(); // Nativo 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 Rolar para o topo
js// jQuery $(window).scrollTop(); // Nativo (document.documentElement && document.documentElement.scrollTop) || document.body.scrollTop;
Manipulação do Dom
3.1 Remover
js// jQuery $el.remove(); // Nativo el.parentNode.removeChild(el);3.2 Texto
Obter texto
js// jQuery $el.text(); // Nativo el.textContent;Definir texto
js// jQuery $el.text(string); // Nativo el.textContent = string;
3.3 HTML
Obter HTML
js// jQuery $el.html(); // Nativo el.innerHTML;Definir HTML
js// jQuery $el.html(htmlString); // Nativo el.innerHTML = htmlString;
3.4 Append
Incluir elemento filho após o último filho do elemento pai.
js// jQuery $el.append("hello"); // Nativo let newEl = document.createElement('div'); newEl.setAttribute('id', 'container'); newEl.innerHTML = 'hello'; el.appendChild(newEl);3.5 Prepend
js// jQuery $el.prepend("hello"); // Nativo let newEl = document.createElement('div'); newEl.setAttribute('id', 'container'); newEl.innerHTML = 'hello'; el.insertBefore(newEl, el.firstChild);3.6 insertBefore
Insere um novo nó antes dos elementos selecionados.
js// jQuery $newEl.insertBefore(queryString); // Nativo const target = document.querySelector(queryString); target.parentNode.insertBefore(newEl, target);3.7 insertAfter
Insere um novo nó após os elementos selecionados.
js// jQuery $newEl.insertAfter(queryString); // Nativo const target = document.querySelector(queryString); target.parentNode.insertBefore(newEl, target.nextSibling);
Ajax
Substitua por fetch e fetch-jsonp
Eventos
Para uma substituição completa com namespace e delegation, consulte https://github.com/oneuijs/oui-dom-events
5.1
Bindnum evento comonjs// jQuery $el.on(eventName, eventHandler); // Nativo el.addEventListener(eventName, eventHandler);5.2
Unbindnum evento comoffjs// jQuery $el.off(eventName, eventHandler); // Nativo el.removeEventListener(eventName, eventHandler);5.3 Trigger
js// jQuery $(el).trigger('custom-event', {key1: 'data'}); // Nativo if (window.CustomEvent) { const event = new CustomEvent('custom-event', {detail: {key1: 'data'}}); } else { const event = document.createEvent('CustomEvent'); event.initCustomEvent('custom-event', true, true, {key1: 'data'}); } el.dispatchEvent(event);
Utilitários
6.1 isArray
js// jQuery $.isArray(range); // Nativo Array.isArray(range);6.2 Trim
js// jQuery $.trim(string); // Nativo string.trim();6.3 Object Assign
Use o polyfill
object.assignpara eetender um Object: https://github.com/ljharb/object.assignjs// jQuery $.extend({}, defaultOpts, opts); // Nativo Object.assign({}, defaultOpts, opts);6.4 Contains
js// jQuery $.contains(el, child); // Nativo el !== child && el.contains(child);
Suporte dos Navegadores
| | | |
--- | --- | --- | --- | --- |
Latest ✔ | Latest ✔ | 10+ ✔ | Latest ✔ | 6.1+ ✔ |
Licença
MIT
File: README.zh-CN.md
你也许不需要 jQuery (You (Might) Don't Need jQuery)
前端发展很快,现代浏览器原生 API 已经足够好用。我们并不需要为了操作 DOM、Event 等再学习一下 jQuery 的 API。同时由于 React、Angular、Vue 等框架的流行,直接操作 DOM 不再是好的模式,jQuery 使用场景大大减少。本项目总结了大部分 jQuery API 替代的方法,暂时只支持 IE10 以上浏览器。
目录
翻译
- 한국어
- 正體中文
- 简体中文
- Bahasa Melayu
- Bahasa Indonesia
- Português(PT-BR)
- Tiếng Việt Nam
- Español
- Русский
- Кыргызча
- Türkçe
- Italiano
- Français
- 日本語
- Polski
Query 选择器
常用的 class、id、属性 选择器都可以使用 document.querySelector 或 document.querySelectorAll 替代。区别是
document.querySelector返回第一个匹配的 Elementdocument.querySelectorAll返回所有匹配的 Element 组成的 NodeList。它可以通过[].slice.call()把它转成 Array- 如果匹配不到任何 Element,jQuery 返回空数组
[],但document.querySelector返回null,注意空指针异常。当找不到时,也可以使用||设置默认的值,如document.querySelectorAll(selector) || []
注意:
document.querySelector和document.querySelectorAll性能很差。如果想提高性能,尽量使用document.getElementById、document.getElementsByClassName或document.getElementsByTagName。
1.0 选择器查询
js// jQuery $('selector'); // Native document.querySelectorAll('selector');1.1 class 查询
js// jQuery $('.class'); // Native document.querySelectorAll('.class'); // or document.getElementsByClassName('class');1.2 id 查询
js// jQuery $('#id'); // Native document.querySelector('#id'); // or document.getElementById('id'); // or window['id']1.3 属性查询
js// jQuery $('a[target=_blank]'); // Native document.querySelectorAll('a[target=_blank]');1.4 后代查询
js// jQuery $el.find('li'); // Native el.querySelectorAll('li');1.5 兄弟及上下元素
兄弟元素
js// 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 );上一个元素
js// jQuery $el.prev(); // Native el.previousElementSibling;下一个元素
js// next $el.next(); // Native el.nextElementSibling;
1.6 Closest
Closest 获得匹配选择器的第一个祖先元素,从当前元素开始沿 DOM 树向上。
js// jQuery $el.closest(queryString); // 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
获取当前每一个匹配元素集的祖先,不包括匹配元素的本身。
js// 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
js// jQuery $('#my-input').val(); // Native document.querySelector('#my-input').value;获取 e.currentTarget 在
.radio中的数组索引js// jQuery $('.radio').index(e.currentTarget); // Native Array.prototype.indexOf.call(document.querySelectorAll('.radio'), e.currentTarget);
1.9 Iframe Contents
jQuery 对象的 iframe
contents()返回的是 iframe 内的documentIframe contents
js// jQuery $iframe.contents(); // Native iframe.contentDocument;Iframe Query
js// jQuery $iframe.contents().find('.css'); // Native iframe.contentDocument.querySelectorAll('.css');
1.10 获取 body
js// jQuery $('body'); // Native document.body;1.11 获取或设置属性
获取属性
js// jQuery $el.attr('foo'); // Native el.getAttribute('foo');设置属性
js// jQuery, note that this works in memory without change the DOM $el.attr('foo', 'bar'); // Native el.setAttribute('foo', 'bar');获取
data-属性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'];
CSS & Style
2.1 CSS
Get style
js// jQuery $el.css("color"); // Native // 注意:此处为了解决当 style 值为 auto 时,返回 auto 的问题 const win = el.ownerDocument.defaultView; // null 的意思是不返回伪类元素 win.getComputedStyle(el, null).color;Set style
js// jQuery $el.css({ color: "#ff0011" }); // Native el.style.color = '#ff0011';Get/Set Styles
注意,如果想一次设置多个 style,可以参考 oui-dom-utils 中 setStyles 方法
Add class
js// jQuery $el.addClass(className); // Native el.classList.add(className);Remove class
js// jQuery $el.removeClass(className); // Native el.classList.remove(className);has class
js// jQuery $el.hasClass(className); // Native el.classList.contains(className);Toggle class
js// jQuery $el.toggleClass(className); // Native el.classList.toggle(className);
2.2 Width & Height
Width 与 Height 获取方法相同,下面以 Height 为例:
Window height
js// window height $(window).height(); // 不含 scrollbar,与 jQuery 行为一致 window.document.documentElement.clientHeight; // 含 scrollbar window.innerHeight;Document height
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 );Element height
js// jQuery $el.height(); // Native function getHeight(el) { const styles = this.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; } // 精确到整数(border-box 时为 height - border 值,content-box 时为 height + padding 值) el.clientHeight; // 精确到小数(border-box 时为 height 值,content-box 时为 height + padding + border 值) el.getBoundingClientRect().height;
2.3 Position & Offset
Position
获得匹配元素相对父元素的偏移
js// jQuery $el.position(); // Native { left: el.offsetLeft, top: el.offsetTop }Offset
获得匹配元素相对文档的偏移
js// 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
获取元素滚动条垂直位置。
js// jQuery $(window).scrollTop(); // Native (document.documentElement && document.documentElement.scrollTop) || document.body.scrollTop;
DOM 操作
3.1 Remove
从 DOM 中移除元素。
js// jQuery $el.remove(); // Native el.parentNode.removeChild(el); // Native - Only latest, NO IE el.remove();3.2 Text
Get text
返回指定元素及其后代的文本内容。
js// jQuery $el.text(); // Native el.textContent;Set text
设置元素的文本内容。
js// jQuery $el.text(string); // Native el.textContent = string;
3.3 HTML
Get HTML
js// jQuery $el.html(); // Native el.innerHTML;Set HTML
js// jQuery $el.html(htmlString); // Native el.innerHTML = htmlString;
3.4 Append
Append 插入到子节点的末尾
js// jQuery $el.append("hello"); // Native (HTML string) el.insertAdjacentHTML('beforeend', 'Hello World'); // Native (Element) el.appendChild(newEl);3.5 Prepend
js// jQuery $el.prepend("hello"); // Native (HTML string) el.insertAdjacentHTML('afterbegin', 'Hello World'); // Native (Element) el.insertBefore(newEl, el.firstChild);3.6 insertBefore
在选中元素前插入新节点
js// jQuery $newEl.insertBefore(queryString); // Native (HTML string) el.insertAdjacentHTML('beforebegin ', 'Hello World'); // Native (Element) const el = document.querySelector(selector); if (el.parentNode) { el.parentNode.insertBefore(newEl, el); }3.7 insertAfter
在选中元素后插入新节点
js// jQuery $newEl.insertAfter(queryString); // Native (HTML string) el.insertAdjacentHTML('afterend', 'Hello World'); // Native (Element) const el = document.querySelector(selector); if (el.parentNode) { el.parentNode.insertBefore(newEl, el.nextSibling); }3.8 is
如果匹配给定的选择器,返回true
js// jQuery $el.is(selector); // Native el.matches(selector);3.9 clone
深拷贝被选元素。(生成被选元素的副本,包含子节点、文本和属性。)
js//jQuery $el.clone(); //Native //深拷贝添加参数'true' el.cloneNode();3.10 empty
移除所有子节点
js//jQuery $el.empty(); //Native el.innerHTML = '';3.11 wrap
把每个被选元素放置在指定的HTML结构中。
js//jQuery $(".inner").wrap(''); //Native Array.from(document.querySelectorAll('.inner')).forEach((el) => { const wrapper = document.createElement('div'); wrapper.className = 'wrapper'; el.parentNode.insertBefore(wrapper, el); el.parentNode.removeChild(el); wrapper.appendChild(el); });3.12 unwrap
移除被选元素的父元素的DOM结构
js// jQuery $('.inner').unwrap(); // Native Array.prototype.forEach.call(document.querySelectorAll('.inner'), (el) => { let elParentNode = el.parentNode if(elParentNode !== document.body) { elParentNode.parentNode.insertBefore(el, elParentNode) elParentNode.parentNode.removeChild(elParentNode) } });3.13 replaceWith
用指定的元素替换被选的元素
js//jQuery $('.inner').replaceWith(''); //Native Array.prototype.forEach.call(document.querySelectorAll('.inner'),(el) => { const outer = document.createElement("div"); outer.className = "outer"; el.parentNode.insertBefore(outer, el); el.parentNode.removeChild(el); });3.14 simple parse
解析 HTML/SVG/XML 字符串
js// jQuery $(`<ol> <li>a</li> <li>b</li> </ol> <ol> <li>c</li> <li>d</li> </ol>`); // Native range = document.createRange(); parse = range.createContextualFragment.bind(range); parse(`<ol> <li>a</li> <li>b</li> </ol> <ol> <li>c</li> <li>d</li> </ol>`);
Ajax
Fetch API 是用于替换 XMLHttpRequest 处理 ajax 的新标准,Chrome 和 Firefox 均支持,旧浏览器可以使用 polyfills 提供支持。
IE9+ 请使用 github/fetch,IE8+ 请使用 fetch-ie8,JSONP 请使用 fetch-jsonp。
4.1 从服务器读取数据并替换匹配元素的内容。
js// jQuery $(selector).load(url, completeCallback) // Native fetch(url).then(data => data.text()).then(data => { document.querySelector(selector).innerHTML = data }).then(completeCallback)
事件
完整地替代命名空间和事件代理,链接到 https://github.com/oneuijs/oui-dom-events
5.0 Document ready by
DOMContentLoadedjs// jQuery $(document).ready(eventHandler); // Native // 检测 DOMContentLoaded 是否已完成 if (document.readyState !== 'loading') { eventHandler(); } else { document.addEventListener('DOMContentLoaded', eventHandler); }5.1 使用 on 绑定事件
js// jQuery $el.on(eventName, eventHandler); // Native el.addEventListener(eventName, eventHandler);5.2 使用 off 解绑事件
js// jQuery $el.off(eventName, eventHandler); // Native el.removeEventListener(eventName, eventHandler);5.3 Trigger
js// jQuery $(el).trigger('custom-event', {key1: 'data'}); // Native if (window.CustomEvent) { const event = new CustomEvent('custom-event', {detail: {key1: 'data'}}); } else { const event = document.createEvent('CustomEvent'); event.initCustomEvent('custom-event', true, true, {key1: 'data'}); } el.dispatchEvent(event);
实用工具
大部分实用工具都能在 native API 中找到. 其他高级功能可以选用专注于该领域的稳定性和性能都更好的库来代替,推荐 lodash。
6.1 基本工具
- isArray
检测参数是不是数组。
js// jQuery $.isArray(range); // Native Array.isArray(range);- isWindow
检测参数是不是 window。
js// jQuery $.isWindow(obj); // Native function isWindow(obj) { return obj !== null && obj !== undefined && obj === obj.window; }- inArray
在数组中搜索指定值并返回索引 (找不到则返回 -1)。
js// jQuery $.inArray(item, array); // Native array.indexOf(item) > -1; // ES6-way array.includes(item);- isNumeric
检测传入的参数是不是数字。
Usetypeofto decide the type or thetypeexample for better accuracy.js// jQuery $.isNumeric(item); // Native function isNumeric(value) { return !isNaN(parseFloat(value)) && isFinite(value); }- isFunction
检测传入的参数是不是 JavaScript 函数对象。
js// jQuery $.isFunction(item); // Native function isFunction(item) { if (typeof item === 'function') { return true; } var type = Object.prototype.toString(item); return type === '[object Function]' || type === '[object GeneratorFunction]'; }- isEmptyObject
检测对象是否为空 (包括不可枚举属性)。
js// jQuery $.isEmptyObject(obj); // Native function isEmptyObject(obj) { return Object.keys(obj).length === 0; }- isPlainObject
检测是不是扁平对象 (使用 “{}” 或 “new Object” 创建)。
js// jQuery $.isPlainObject(obj); // Native function isPlainObject(obj) { if (typeof (obj) !== 'object' || obj.nodeType || obj !== null && obj !== undefined && obj === obj.window) { return false; } if (obj.constructor && !Object.prototype.hasOwnProperty.call(obj.constructor.prototype, 'isPrototypeOf')) { return false; } return true; }- extend
合并多个对象的内容到第一个对象。
object.assign 是 ES6 API,也可以使用 polyfill。js// jQuery $.extend({}, defaultOpts, opts); // Native Object.assign({}, defaultOpts, opts);- trim
移除字符串头尾空白。
js// jQuery $.trim(string); // Native string.trim();- map
将数组或对象转化为包含新内容的数组。
js// jQuery $.map(array, (value, index) => { }); // Native array.map((value, index) => { });- each
轮询函数,可用于平滑的轮询对象和数组。
js// jQuery $.each(array, (index, value) => { }); // Native array.forEach((value, index) => { });- grep
找到数组中符合过滤函数的元素。
js// jQuery $.grep(array, (value, index) => { }); // Native array.filter((value, index) => { });- type
检测对象的 JavaScript [Class] 内部类型。
js// jQuery $.type(obj); // Native function type(item) { const reTypeOf = /(?:^\[object\s(.*?)\]$)/; return Object.prototype.toString.call(item) .replace(reTypeOf, '$1') .toLowerCase(); }- merge
合并第二个数组内容到第一个数组。
js// jQuery $.merge(array1, array2); // Native // 使用 concat,不能去除重复值 function merge(...args) { return [].concat(...args) } // ES6,同样不能去除重复值 array1 = [...array1, ...array2] // 使用 Set,可以去除重复值 function merge(...args) { return Array.from(new Set([].concat(...args))) }- now
返回当前时间的数字呈现。
js// jQuery $.now(); // Native Date.now();- proxy
传入函数并返回一个新函数,该函数绑定指定上下文。
js// jQuery $.proxy(fn, context); // Native fn.bind(context);- makeArray
类数组对象转化为真正的 JavaScript 数组。
js// jQuery $.makeArray(arrayLike); // Native Array.prototype.slice.call(arrayLike); // ES6-way Array.from(arrayLike);6.2 包含
检测 DOM 元素是不是其他 DOM 元素的后代。
js// jQuery $.contains(el, child); // Native el !== child && el.contains(child);6.3 Globaleval
全局执行 JavaScript 代码。
js// jQuery $.globaleval(code); // Native function Globaleval(code) { const script = document.createElement('script'); script.text = code; document.head.appendChild(script).parentNode.removeChild(script); } // Use eval, but context of eval is current, context of $.Globaleval is global. eval(code);6.4 解析
- parseHTML
解析字符串为 DOM 节点数组。
js// jQuery $.parseHTML(htmlString); // Native function parseHTML(string) { const context = document.implementation.createHTMLDocument(); // Set the base href for the created document so any parsed elements with URLs // are based on the document's URL const base = context.createElement('base'); base.href = document.location.href; context.head.appendChild(base); context.body.innerHTML = string; return context.body.children; }- parseJSON
传入格式正确的 JSON 字符串并返回 JavaScript 值。
js// jQuery $.parseJSON(str); // Native JSON.parse(str);
Promises
Promise 代表异步操作的最终结果。jQuery 用它自己的方式处理 promises,原生 JavaScript 遵循 Promises/A+ 标准实现了最小 API 来处理 promises。
7.1 done, fail, always
done会在 promise 解决时调用,fail会在 promise 拒绝时调用,always总会调用。js// jQuery $promise.done(doneCallback).fail(failCallback).always(alwaysCallback) // Native promise.then(doneCallback, failCallback).then(alwaysCallback, alwaysCallback)7.2 when
when用于处理多个 promises。当全部 promises 被解决时返回,当任一 promise 被拒绝时拒绝。js// jQuery $.when($promise1, $promise2).done((promise1Result, promise2Result) => { }); // Native Promise.all([$promise1, $promise2]).then([promise1Result, promise2Result] => {});7.3 Deferred
Deferred 是创建 promises 的一种方式。
js// jQuery function asyncFunc() { const defer = new $.Deferred(); setTimeout(() => { if(true) { defer.resolve('some_value_computed_asynchronously'); } else { defer.reject('failed'); } }, 1000); return defer.promise(); } // Native function asyncFunc() { return new Promise((resolve, reject) => { setTimeout(() => { if (true) { resolve('some_value_computed_asynchronously'); } else { reject('failed'); } }, 1000); }); } // Deferred way function defer() { const deferred = {}; const promise = new Promise((resolve, reject) => { deferred.resolve = resolve; deferred.reject = reject; }); deferred.promise = () => { return promise; }; return deferred; } function asyncFunc() { const defer = defer(); setTimeout(() => { if(true) { defer.resolve('some_value_computed_asynchronously'); } else { defer.reject('failed'); } }, 1000); return defer.promise(); }
动画
8.1 Show & Hide
js// jQuery $el.show(); $el.hide(); // Native // 更多 show 方法的细节详见 https://github.com/oneuijs/oui-dom-utils/blob/master/src/index.js#L363 el.style.display = ''|'inline'|'inline-block'|'inline-table'|'block'; el.style.display = 'none';8.2 Toggle
显示或隐藏元素。
js// jQuery $el.toggle(); // Native if (el.ownerDocument.defaultView.getComputedStyle(el, null).display === 'none') { el.style.display = ''|'inline'|'inline-block'|'inline-table'|'block'; } else { el.style.display = 'none'; }8.3 FadeIn & FadeOut
js// jQuery $el.fadeIn(3000); $el.fadeOut(3000); // Native el.style.transition = 'opacity 3s'; // fadeIn el.style.opacity = '1'; // fadeOut el.style.opacity = '0';8.4 FadeTo
调整元素透明度。
js// jQuery $el.fadeTo('slow',0.15); // Native el.style.transition = 'opacity 3s'; // 假设 'slow' 等于 3 秒 el.style.opacity = '0.15';8.5 FadeToggle
动画调整透明度用来显示或隐藏。
js// jQuery $el.fadeToggle(); // Native el.style.transition = 'opacity 3s'; const { opacity } = el.ownerDocument.defaultView.getComputedStyle(el, null); if (opacity === '1') { el.style.opacity = '0'; } else { el.style.opacity = '1'; }8.6 SlideUp & SlideDown
js// jQuery $el.slideUp(); $el.slideDown(); // Native const originHeight = '100px'; el.style.transition = 'height 3s'; // slideUp el.style.height = '0px'; // slideDown el.style.height = originHeight;8.7 SlideToggle
滑动切换显示或隐藏。
js// jQuery $el.slideToggle(); // Native const originHeight = '100px'; el.style.transition = 'height 3s'; const { height } = el.ownerDocument.defaultView.getComputedStyle(el, null); if (parseInt(height, 10) === 0) { el.style.height = originHeight; } else { el.style.height = '0px'; }8.8 Animate
执行一系列 CSS 属性动画。
js// jQuery $el.animate({ params }, speed); // Native el.style.transition = 'all ' + speed; Object.keys(params).forEach((key) => { el.style[key] = params[key]; });
替代品
- 你可能不需要 jQuery (You Might Not Need jQuery) - 如何使用原生 JavaScript 实现通用事件,元素,ajax 等用法。
- npm-dom 以及 webmodules - 在 NPM 上提供独立 DOM 模块的组织
浏览器支持
![]() |
![]() |
![]() |
![]() |
![]() |
|---|---|---|---|---|
| Latest ✔ | Latest ✔ | 10+ ✔ | Latest ✔ | 6.1+ ✔ |
License
MIT
File: README.zh-TW.md
You (Might) Don't Need jQuery
當今的前端環境發展迅速,現代瀏覽器已經提供了夠好用的 DOM/BOM API,我們不需要為了 DOM 操作或事件處理而從頭開始學 jQuery。同時,由於 React、Angular 和 Vue 等前端框架的普及,直接操作 DOM 變成了反模式,jQuery 的使用性大幅減少。本專案概述了大部份 Javascript 替代 jQuery 的方式,支援 IE 10 以上。
備註:jQuery 仍然是一個很棒的函式庫,有很多有效的案例。不用刻意為了變而改變 !
目錄
- Translations
- Query Selector
- CSS & Style
- DOM Manipulation
- Ajax
- Events
- Utilities
- Promises
- Animation
- Alternatives
- 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
常見的 class、id、屬性等選擇器,我們可以使用 document.querySelector 或 document.querySelectorAll 替代。差別是
document.querySelector返回第一個匹配的 Elementdocument.querySelectorAll返回所有匹配的 Element 組成的 NodeList。它可以通過[].slice.call()轉換成 Array 使用- 如果匹配不到任何 Element,jQuery 和
document.querySelectorAll將會返回[],但document.querySelector會返回null。
注意:
document.querySelector和document.querySelectorAll效能很差。如果想提高效能,盡量使用document.getElementById、document.getElementsByClassName或document.getElementsByTagName。
1.0 Query by selector 選擇器查詢
js// jQuery $('selector'); // Native document.querySelectorAll('selector');1.1 Query by class 查詢 class
js// jQuery $('.class'); // Native document.querySelectorAll('.class'); // 或 document.getElementsByClassName('class');1.2 Query by id 查詢 id
js// jQuery $('#id'); // Native document.querySelector('#id'); // 或 document.getElementById('id');1.3 Query by attribute 屬性查詢
js// jQuery $('a[target=_blank]'); // Native document.querySelectorAll('a[target=_blank]');1.4 Query in descendants 後代查詢
js// jQuery $el.find('li'); // Native el.querySelectorAll('li');1.5 Sibling/Previous/Next Elements 同層相鄰及前後元素
All siblings 同層相鄰 (兄弟元素)
js// 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 同層前一個元素
js// jQuery $el.prev(); // Native el.previousElementSibling;Next sibling 同層後一個元素
js// next $el.next(); // Native el.nextElementSibling;All previous siblings 所有同層裡之前的元素
js// jQuery (可選的過濾選擇器) $el.prevAll($filter); // Native (可選的過濾函式) 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// jQuery (可選的過濾選擇器) $el.nextAll($filter); // Native (可選的過濾函式) function getNextSiblings(elem, filter) { var sibs = []; var nextElem = elem.parentNode.firstChild; do { if (nextElem.nodeType === 3) continue; // ignore text nodes if (nextElem === elem) continue; // ignore elem of target if (nextElem === elem.nextElementSibling) { if (!filter || filter(elem)) { sibs.push(nextElem); elem = nextElem; } } } while(nextElem = nextElem.nextSibling) return sibs; }
一個篩選函式範例:
function exampleFilter(elem) {
switch (elem.nodeName.toUpperCase()) {
case 'DIV':
return true;
case 'SPAN':
return true;
default:
return false;
}
}1.6 Closest 遍尋
Closest 返回匹配選擇器的第一個父元素,從當前元素開始沿 DOM 樹向上遍尋。
js// jQuery $el.closest(queryString); // Native - 只支援最新版本,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
獲取當前每一個匹配元素的祖先們,不包含匹配元素本身,DOM node 或 jQuery 物件。
js// jQuery $el.parentsUntil(selector, filter); // Native function parentsUntil(el, selector, filter) { const result = []; const matchesSelector = el.matches || el.webkitMatchesSelector || el.mozMatchesSelector || el.msMatchesSelector; // 從父母開始匹配 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 輸入欄位
js// jQuery $('#my-input').val(); // Native document.querySelector('#my-input').value;獲取 e.currentTarget 在
.radio中的索引值js// 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()在 jQuery 返回的是 iframe 内的documentIframe contents
js// jQuery $iframe.contents(); // Native iframe.contentDocument;Iframe Query
js// jQuery $iframe.contents().find('.css'); // Native iframe.contentDocument.querySelectorAll('.css');
1.10 獲取 body
js// jQuery $('body'); // Native document.body;1.11 獲取或設置屬性
Get an attribute 獲取屬性
js// jQuery $el.attr('foo'); // Native el.getAttribute('foo');Set an attribute 設置屬性
js// jQuery, 請注意,這可以在記憶體中工作,無需更改 DOM $el.attr('foo', 'bar'); // Native el.setAttribute('foo', 'bar');獲取
data-屬性js// jQuery $el.data('foo'); // Native (使用 `getAttribute`) el.getAttribute('data-foo'); // Native (如果只需要支援 IE 11 以上,可以使用 `dataset`) el.dataset['foo'];
1.12 包含字串的選擇器 (區分大小寫)
js// 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); }); }
CSS & Style
2.1 CSS
獲取樣式
js// jQuery $el.css("color"); // Native // 注意: 已知問題,如果樣式的值為 'auto',將會返回 'auto' const win = el.ownerDocument.defaultView; // null 意指不返回偽樣式 win.getComputedStyle(el, null).color;設置樣式
js// jQuery $el.css({ color: "#ff0011" }); // Native el.style.color = '#ff0011';獲取 / 設置樣式
注意:如果想一次設置多個樣式,可以參考 oui-dom-utils 裡 setStyles 的方法
Add class 增加樣式
js// jQuery $el.addClass(className); // Native el.classList.add(className);remove class 移除樣式
js// jQuery $el.removeClass(className); // Native el.classList.remove(className);has class 是否有樣式
js// jQuery $el.hasClass(className); // Native el.classList.contains(className);Toggle class 觸發樣式
js// jQuery $el.toggleClass(className); // Native el.classList.toggle(className);
2.2 Width & Height
Width 與 Height 獲取方式相同,下面以 Height 為例:
Window height
js// window height $(window).height(); // 沒有捲軸,行為像 jQuery window.document.documentElement.clientHeight; // 有捲軸 window.innerHeight;Document height
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 );Element height
js// jQuery $el.height(); // Native function getHeight(el) { const styles = this.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; } // 精準到整數(當 `border-box` 時為 `height - border` 值;當 `content-box` 時為 `height + padding` 值) el.clientHeight; // 精準到小數(當 `border-box` 時為 `height` 值;當 `content-box` 時為 `height + padding + border` 值) el.getBoundingClientRect().height;
2.3 Position & Offset 定位和位移
Position 定位
獲得匹配元素相對於父元素的坐標
js// jQuery $el.position(); // Native { left: el.offsetLeft, top: el.offsetTop }Offset 位移
獲得匹配元素相對於文件的坐標
js// 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
獲取元素滾動條的當前垂直位置。
js// jQuery $(window).scrollTop(); // Native (document.documentElement && document.documentElement.scrollTop) || document.body.scrollTop;
DOM Manipulation DOM 操作
3.1 Remove 移除
從 DOM 中移除元素。
js// jQuery $el.remove(); // Native el.parentNode.removeChild(el);3.2 Text 文字
Get text 獲取文字
返回元素的文本內容,包含其後代。
js// jQuery $el.text(); // Native el.textContent;Set text 設置文字
設置元素的文本內容。
js// jQuery $el.text(string); // Native el.textContent = string;
3.3 HTML
Get HTML 獲取 HTML
js// jQuery $el.html(); // Native el.innerHTML;Set HTML 設置 HTML
js// jQuery $el.html(htmlString); // Native el.innerHTML = htmlString;
3.4 Append 追加
Append 在父元素的最後一個子元素後追加子元素
js// jQuery $el.append("hello"); // Native (HTML 字串) el.insertAdjacentHTML('beforeend', 'Hello World'); // Native (元素) el.appendChild(newEl);3.5 Prepend 前置
js// jQuery $el.prepend("hello"); // Native (HTML 字串) el.insertAdjacentHTML('afterbegin', 'Hello World'); // Native (元素) el.insertBefore(newEl, el.firstChild);3.6 insertBefore 在元素前方插入
在選取的元素前插入新節點
js// jQuery $newEl.insertBefore(queryString); // Native (HTML 字串) el.insertAdjacentHTML('beforebegin ', 'Hello World'); // Native (元素) const el = document.querySelector(selector); if (el.parentNode) { el.parentNode.insertBefore(newEl, el); }3.7 insertAfter 在元素後方插入
在選取的元素插入新節點
js// jQuery $newEl.insertAfter(queryString); // Native (HTML 字串) el.insertAdjacentHTML('afterend', 'Hello World'); // Native (元素) const el = document.querySelector(selector); if (el.parentNode) { el.parentNode.insertBefore(newEl, el.nextSibling); }3.8 is
如果匹配 query selector,返回
truejs// jQuery $el.is(selector); // Native el.matches(selector);3.9 clone
創造一個深拷貝元素:此拷貝包含匹配元素及其所有後代元素和文本節點。
js// jQuery. 將參數設為 `true` 以表示應將事件處理程序與元素一起複製。 $el.clone(); // Native el.cloneNode();3.10 empty
移除所有子節點
// jQuery
$el.empty();
// Native
el.innerHTML = '';- 3.11 wrap
把每個被選取的元素放到指定的 HTML 結構裡
// jQuery
$(".inner").wrap('');
// Native
Array.from(document.querySelectorAll('.inner')).forEach((el) => {
const wrapper = document.createElement('div');
wrapper.className = 'wrapper';
el.parentNode.insertBefore(wrapper, el);
el.parentNode.removeChild(el);
wrapper.appendChild(el);
});3.12 unwrap
從 DOM 結構移除匹配元素的父元素
js// jQuery $('.inner').unwrap(); // Native Array.from(document.querySelectorAll('.inner')).forEach((el) => { let elParentNode = el.parentNode if(elParentNode !== document.body) { elParentNode.parentNode.insertBefore(el, elParentNode) elParentNode.parentNode.removeChild(elParentNode) } });3.13 replaceWith
用提供的新內容取代任何匹配元素集中的每個元素
js// jQuery $('.inner').replaceWith(''); // Native (方案一) - 最新版或 Edge17+ Array.from(document.querySelectorAll('.inner')).forEach((el) => { const outer = document.createElement('div'); outer.className = 'outer'; el.replaceWith(outer); }); // Native Array.from(document.querySelectorAll('.inner')).forEach((el) => { const outer = document.createElement("div"); outer.className = "outer"; el.parentNode.replaceChild(outer, el); });3.14 simple parse
解析 HTML / SVG / XML 字串
js// jQuery $(`<ol> <li>a</li> <li>b</li> </ol> <ol> <li>c</li> <li>d</li> </ol>`); // Native range = document.createRange(); parse = range.createContextualFragment.bind(range); parse(`<ol> <li>a</li> <li>b</li> </ol> <ol> <li>c</li> <li>d</li> </ol>`);
Ajax
Fetch API 是一個用是來替換 XMLHttpRequest 執行 ajax 的新標準。適用於 Chrome 和 Firefox,你可以使用 polyfill 讓它在舊版瀏覽器上運行。。
IE9+ 請使用 github/fetch,IE8+ 請使用 fetch-ie8,JSONP 請使用 fetch-jsonp。
4.1 從伺服器載入數據並將返回的 HTML 放入匹配的元素中。
js// jQuery $(selector).load(url, completeCallback) // Native fetch(url).then(data => data.text()).then(data => { document.querySelector(selector).innerHTML = data }).then(completeCallback)
Events
完整的替代命名空間及事件處理,請參考 https://github.com/oneuijs/oui-dom-events
5.0 Document ready by
DOMContentLoadedjs// jQuery $(document).ready(eventHandler); // Native // 檢查 DOMContentLoaded 是否已經完成 if (document.readyState !== 'loading') { eventHandler(); } else { document.addEventListener('DOMContentLoaded', eventHandler); }5.1 使用 on 綁定事件
js// jQuery $el.on(eventName, eventHandler); // Native el.addEventListener(eventName, eventHandler);5.2 使用 off 綁定事件
js// jQuery $el.off(eventName, eventHandler); // Native el.removeEventListener(eventName, eventHandler);5.3 Trigger
js// jQuery $(el).trigger('custom-event', {key1: 'data'}); // Native if (window.CustomEvent) { const event = new CustomEvent('custom-event', {detail: {key1: 'data'}}); } else { const event = document.createEvent('CustomEvent'); event.initCustomEvent('custom-event', true, true, {key1: 'data'}); } el.dispatchEvent(event);
Utilities
大部份的 jQuery 實用工具都能在 native API 中找到。其它進階功能可以選用專注於穩定及效能的優質工具庫,推薦 lodash。
6.1 基本工具
- isArray
判斷參數是否為陣列。
js// jQuery $.isArray(array); // Native Array.isArray(array);- isWindow
判斷參數是否為 window
js// jQuery $.isWindow(obj); // Native function isWindow(obj) { return obj !== null && obj !== undefined && obj === obj.window; }- inArray
在陣列中搜尋指定值並返回索引值 (找不到則返回 -1)。
js// jQuery $.inArray(item, array); // Native array.indexOf(item) > -1; // ES6-way array.includes(item);- isNumeric
判斷傳入的參數是否為數字。
為了更好的準確性,請使用typeof確定型別,或參考下方type範例。js// jQuery $.isNumeric(item); // Native function isNumeric(n) { return !isNaN(parseFloat(n)) && isFinite(n); }- isFunction
判斷傳入的參數是否為 Javascript 函式。
js// jQuery $.isFunction(item); // Native function isFunction(item) { if (typeof item === 'function') { return true; } var type = Object.prototype.toString.call(item); return type === '[object Function]' || type === '[object GeneratorFunction]'; }- isEmptyObject
檢測物件是否為空值 (包含不可枚舉的屬性)
js// jQuery $.isEmptyObject(obj); // Native function isEmptyObject(obj) { return Object.keys(obj).length === 0; }- isPlainObject
檢測物件是否為純對象 (使用 “{}” 或 “new Object” 創建)
js// jQuery $.isPlainObject(obj); // Native function isPlainObject(obj) { if (typeof (obj) !== 'object' || obj.nodeType || obj !== null && obj !== undefined && obj === obj.window) { return false; } if (obj.constructor && !Object.prototype.hasOwnProperty.call(obj.constructor.prototype, 'isPrototypeOf')) { return false; } return true; }- extend
將二個或多個物件的內容合併到一個新物件中,且不修改任一個參數。
object.assign 是 ES6 API,你也可以使用 polyfill。js// jQuery $.extend({}, object1, object2); // Native Object.assign({}, object1, object2);- trim
刪除字串開頭和結尾的空白。
js// jQuery $.trim(string); // Native string.trim();- map
將陣列或物件裡的所有項目轉換為新的陣列項目。
js// jQuery $.map(array, (value, index) => { }); // Native array.map((value, index) => { });- each
通用迭代函式,可用於無縫迭代物件或陣列。
js// jQuery $.each(array, (index, value) => { }); // Native array.forEach((value, index) => { });- grep
找到陣列中符合過濾函式的元素。
js// jQuery $.grep(array, (value, index) => { }); // Native array.filter((value, index) => { });- type
檢測物件中的 JavaScript [Class] 內部型態。
js// jQuery $.type(obj); // Native function type(item) { const reTypeOf = /(?:^\[object\s(.*?)\]$)/; return Object.prototype.toString.call(item) .replace(reTypeOf, '$1') .toLowerCase(); }- merge
將二個陣列的內容合併到第一個陣列裡。
js// jQuery, 不會刪除重複的項目 $.merge(array1, array2); // Native, 不會刪除重複的項目 function merge(...args) { return [].concat(...args) } // ES6-way, 不會刪除重複的項目 array1 = [...array1, ...array2] // Set version, 不會刪除重複的項目 function merge(...args) { return Array.from(new Set([].concat(...args))) }- now
返回表示當前時間的數字。
js// jQuery $.now(); // Native Date.now();- proxy
傳入一個函式並返回一個新的函式,該函式綁定指定的上下文。
js// jQuery $.proxy(fn, context); // Native fn.bind(context);將類似陣列的物件轉換為真正的 JavaScript 陣列。
js// jQuery $.makeArray(arrayLike); // Native Array.prototype.slice.call(arrayLike); // ES6-way: Array.from() method Array.from(arrayLike); // ES6-way: spread operator 展開運算式 [...arrayLike];6.2 Contains
檢查 DOM 元素是否為其它 DOM 元素的後代。
js// jQuery $.contains(el, child); // Native el !== child && el.contains(child);6.3 Globaleval
執行一些 JavaScript 的全域域代碼。
js// jQuery $.globaleval(code); // Native function Globaleval(code) { const script = document.createElement('script'); script.text = code; document.head.appendChild(script).parentNode.removeChild(script); } // 使用 eval,但 eval 的上下文是當前的,而 $.Globaleval 的上下文是 global 全域的。 eval(code);6.4 parse
- parseHTML
將字串解析為 DOM nodes 陣列。
js// jQuery $.parseHTML(htmlString); // Native function parseHTML(string) { const context = document.implementation.createHTMLDocument(); // Set the base href for the created document so any parsed elements with URLs // are based on the document's URL const base = context.createElement('base'); base.href = document.location.href; context.head.appendChild(base); context.body.innerHTML = string; return context.body.children; }6.5 exists
exists
檢查元素是否存在於 DOM 裡。
js// jQuery if ($('selector').length) { // exists } // Native var element = document.getElementById('elementId'); if (typeof(element) != 'undefined' && element != null) { // exists }
Promises
promise 表示異步操作的最終結果。 jQuery 用它自己的方式來處理 promises。原生 JavaScript 依據 Promises/A+ 標準來實現最小 API 處理 promises。
7.1 done, fail, always
done會在 promise 解決時調用,fail會在 promise 拒絕時調用,always無論 promise 解決或拒絕時都會調用。js// jQuery $promise.done(doneCallback).fail(failCallback).always(alwaysCallback) // Native promise.then(doneCallback, failCallback).then(alwaysCallback, alwaysCallback)7.2 when
when用於處理多個 promises。當全部 promises 被解決時返回,當任一 promises 被拒絕時拒絕。js// jQuery $.when($promise1, $promise2).done((promise1Result, promise2Result) => { }); // Native Promise.all([$promise1, $promise2]).then([promise1Result, promise2Result] => {});7.3 Deferred
Deferred 是創建 promises 的一種方式。
js// jQuery function asyncFunc() { const defer = new $.Deferred(); setTimeout(() => { if(true) { defer.resolve('some_value_computed_asynchronously'); } else { defer.reject('failed'); } }, 1000); return defer.promise(); } // Native function asyncFunc() { return new Promise((resolve, reject) => { setTimeout(() => { if (true) { resolve('some_value_computed_asynchronously'); } else { reject('failed'); } }, 1000); }); } // Deferred way function defer() { const deferred = {}; const promise = new Promise((resolve, reject) => { deferred.resolve = resolve; deferred.reject = reject; }); deferred.promise = () => { return promise; }; return deferred; } function asyncFunc() { const defer = defer(); setTimeout(() => { if(true) { defer.resolve('some_value_computed_asynchronously'); } else { defer.reject('failed'); } }, 1000); return defer.promise(); }
Animation
8.1 Show & Hide
js// jQuery $el.show(); $el.hide(); // Native // 更多 show 方法的細節,請參考 https://github.com/oneuijs/oui-dom-utils/blob/master/src/index.js#L363 el.style.display = ''|'inline'|'inline-block'|'inline-table'|'block'; el.style.display = 'none';8.2 Toggle
顯示或隱藏元素。
js// jQuery $el.toggle(); // Native if (el.ownerDocument.defaultView.getComputedStyle(el, null).display === 'none') { el.style.display = ''|'inline'|'inline-block'|'inline-table'|'block'; } else { el.style.display = 'none'; }8.3 FadeIn & FadeOut
js// jQuery $el.fadeIn(3000); $el.fadeOut(3000); // Native fadeOut function fadeOut(el, ms) { if (ms) { el.style.transition = `opacity ${ms} ms`; el.addEventListener( 'transitionend', function(event) { el.style.display = 'none'; }, false ); } el.style.opacity = '0'; } // Native fadeIn function fadeIn(elem, ms) { elem.style.opacity = 0; if (ms) { let opacity = 0; const timer = setInterval(function() { opacity += 50 / ms; if (opacity >= 1) { clearInterval(timer); opacity = 1; } elem.style.opacity = opacity; }, 50); } else { elem.style.opacity = 1; } }8.4 FadeTo
調整元素的透明度。
js// jQuery $el.fadeTo('slow',0.15); // Native el.style.transition = 'opacity 3s'; // assume 'slow' equals 3 seconds el.style.opacity = '0.15';8.5 FadeToggle
動畫調整透明度來顯示或隱藏。
js// jQuery $el.fadeToggle(); // Native el.style.transition = 'opacity 3s'; const { opacity } = el.ownerDocument.defaultView.getComputedStyle(el, null); if (opacity === '1') { el.style.opacity = '0'; } else { el.style.opacity = '1'; }8.6 SlideUp & SlideDown
js// jQuery $el.slideUp(); $el.slideDown(); // Native const originHeight = '100px'; el.style.transition = 'height 3s'; // slideUp el.style.height = '0px'; // slideDown el.style.height = originHeight;8.7 SlideToggle
滑動效果來顯示或隱藏元素。
js// jQuery $el.slideToggle(); // Native const originHeight = '100px'; el.style.transition = 'height 3s'; const { height } = el.ownerDocument.defaultView.getComputedStyle(el, null); if (parseInt(height, 10) === 0) { el.style.height = originHeight; } else { el.style.height = '0px'; }8.8 Animate
執行一組自定義動畫的 CSS 屬性。
js// jQuery $el.animate({ params }, speed); // Native el.style.transition = 'all ' + speed; Object.keys(params).forEach((key) => { el.style[key] = params[key]; });
Alternatives
- You Might Not Need jQuery - Examples of how to do common event, element, ajax etc with plain javascript.
- npm-dom and webmodules - Organizations you can find individual DOM modules on NPM
Browser Support
![]() |
![]() |
![]() |
![]() |
![]() |
|---|---|---|---|---|
| Latest ✔ | Latest ✔ | 10+ ✔ | Latest ✔ | 6.1+ ✔ |
License
MIT
File: README-es.md
Tú no necesitas jQuery
El desarrollo Frontend evoluciona día a día, y los navegadores modernos ya han implementado nativamente APIs para trabajar con DOM/BOM, las cuales son muy buenas, por lo que definitivamente no es necesario aprender jQuery desde cero para manipular el DOM. En la actualidad, gracias al surgimiento de librerías frontend como React, Angular y Vue, manipular el DOM es contrario a los patrones establecidos, y jQuery se ha vuelto menos importante. Este proyecto resume la mayoría de métodos alternativos a jQuery, pero de forma nativa con soporte IE 10+.
Tabla de Contenidos
- Traducción
- Query Selector
- CSS & Estilo
- Manipulación DOM
- Ajax
- Eventos
- Utilidades
- Promesas
- Animaciones
- Alternativas
- Navegadores soportados
Traducción
- 한국어
- 正體中文
- 简体中文
- Bahasa Melayu
- Bahasa Indonesia
- Português(PT-BR)
- Tiếng Việt Nam
- Español
- Русский
- Кыргызча
- Türkçe
- Italiano
- Français
- 日本語
- Polski
Query Selector
En lugar de los selectores comunes como clase, id o atributos podemos usar document.querySelector o document.querySelectorAll como alternativas. Las diferencias radican en:
document.querySelectordevuelve el primer elemento que cumpla con la condicióndocument.querySelectorAlldevuelve todos los elementos que cumplen con la condición en forma de NodeList. Puede ser convertido a Array usando[].slice.call(document.querySelectorAll(selector) || []);- Si ningún elemento cumple con la condición, jQuery retornaría
[]mientras la API DOM retornaríanull. Nótese el NullPointerException. Se puede usar||para establecer el valor por defecto al no encontrar elementos, como endocument.querySelectorAll(selector) || []
Nota: document.querySelector y document.querySelectorAll son bastante LENTOS, procuree utilizar getElementById, document.getElementsByClassName o document.getElementsByTagName si desea obtener un mejor rendimiento.
1.0 Buscar por selector
js// jQuery $('selector'); // Nativo document.querySelectorAll('selector');1.1 Buscar por Clase
js// jQuery $('.class'); // Nativo document.querySelectorAll('.class'); // Forma alternativa document.getElementsByClassName('class');1.2 Buscar por id
js// jQuery $('#id'); // Nativo document.querySelector('#id'); // Forma alternativa document.getElementById('id');1.3 Buscar por atributo
js// jQuery $('a[target=_blank]'); // Nativo document.querySelectorAll('a[target=_blank]');1.4 Buscar en descendientes
js// jQuery $el.find('li'); // Nativo el.querySelectorAll('li');1.5 Elementos Hermanos/Previos/Siguientes
Elementos hermanos
js// jQuery $el.siblings(); // Nativo Array.prototype.filter.call(el.parentNode.children, (child) => child !== el );Elementos previos
js// jQuery $el.prev(); // Nativo el.previousElementSibling;Elementos siguientes
js// jQuery $el.next(); // Nativo el.nextElementSibling;
1.6 Más cercano
Retorna el elemento más cercano que coincida con la condición, partiendo desde el nodo actual hasta document.
js// jQuery $el.closest(selector); // Nativo - Sólo el último, NO IE el.closest(selector); // Nativo - 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 Padres hasta
Obtiene los ancestros de cada elemento en el set actual de elementos que cumplan con la condición, sin incluir el actual
js// jQuery $el.parentsUntil(selector, filter); // Nativo function parentsUntil(el, selector, filter) { const result = []; const matchesSelector = el.matches || el.webkitMatchesSelector || el.mozMatchesSelector || el.msMatchesSelector; // Partir desde el elemento padre 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 Formularios
Input/Textarea
js// jQuery $('#my-input').val(); // Nativo document.querySelector('#my-input').value;Obtener el índice de e.currentTarget en
.radiojs// jQuery $('.radio').index(e.currentTarget); // Nativo Array.prototype.indexOf.call(document.querySelectorAll('.radio'), e.currentTarget);
1.9 Contenidos de Iframe
$('iframe').contents()devuelvecontentDocumentpara este iframe específicoContenidos de Iframe
js// jQuery $iframe.contents(); // Nativo iframe.contentDocument;Buscar dentro de un Iframe
js// jQuery $iframe.contents().find('.css'); // Nativo iframe.contentDocument.querySelectorAll('.css');
1.10 Obtener body
js// jQuery $('body'); // Nativo document.body;1.11 Obtener y establecer atributos
Obtener un atributo
js// jQuery $el.attr('foo'); // Nativo el.getAttribute('foo');Establecer un atributo
js// jQuery, note que esto funciona en memoria sin cambiar el DOM $el.attr('foo', 'bar'); // Nativo el.setAttribute('foo', 'bar');Obtener un atributo
data-js// jQuery $el.data('foo'); // Nativo el.getAttribute('data-foo'); // Nativo (Utilice `dataset` solamente si necesita dar soporte a IE 11+) el.dataset['foo'];
CSS & Estilo
2.1 CSS
Obtener Estilo
js// jQuery $el.css("color"); // Nativo // NOTA: Bug conocido, retornará 'auto' si el valor de estilo es 'auto' const win = el.ownerDocument.defaultView; // null significa que no retorne pseudo estilos win.getComputedStyle(el, null).color;Establecer estilo
js// jQuery $el.css({ color: "#ff0011" }); // Nativo el.style.color = '#ff0011';Obtener/Establecer Estilos
Nótese que si se desea establecer múltiples estilos a la vez, se puede utilizar el método setStyles en el paquete oui-dom-utils.
Agregar clase
js// jQuery $el.addClass(className); // Nativo el.classList.add(className);Quitar Clase
js// jQuery $el.removeClass(className); // Nativo el.classList.remove(className);Consultar si tiene clase
js// jQuery $el.hasClass(className); // Nativo el.classList.contains(className);Toggle class
js// jQuery $el.toggleClass(className); // Nativo el.classList.toggle(className);
2.2 Width & Height
Ancho y Alto son teóricamente idénticos. Usaremos el Alto como ejemplo:
Alto de Ventana
js// alto de ventana $(window).height(); // Con scrollbar, se comporta como jQuery window.document.documentElement.clientHeight; // Sin scrollbar window.innerHeight;Alto de Documento
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 );Alto de Elemento
js// jQuery $el.height(); // Nativo 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; } // Precisión de entero(para `border-box`, es `height - border`; con content-box`, es `height + padding`) el.clientHeight; // Precisión de decimal(para `border-box`, es `height`; con `content-box`, es `height + padding + border`) el.getBoundingClientRect().height;
2.3 Posición y Offset
Posición
Obtiene las coordenadas actuales del elemento, en relación con el padre.
js// jQuery $el.position(); // Nativo { left: el.offsetLeft, top: el.offsetTop }Offset
Obtiene las coordenadas actuales del elemento, en relación con el documento.
js// jQuery $el.offset(); // Nativo 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 Posición vertical del scroll
Obtiene la posición vertical actual de la barra de scroll para el elemento.
js// jQuery $(window).scrollTop(); // Nativo (document.documentElement && document.documentElement.scrollTop) || document.body.scrollTop;
Manipulación DOM
3.1 Eliminar
Elimina el elemento del DOM
js// jQuery $el.remove(); // Nativo el.parentNode.removeChild(el);3.2 Texto
Obtener Texto
Obtiene los contenidos de texto combinado del elemento, incluyendo sus decendientes.
js// jQuery $el.text(); // Nativo el.textContent;Establecer Texto
Establece el contenido del elemento al texto especificado
js// jQuery $el.text(string); // Nativo el.textContent = string;
3.3 HTML
Obtener HTML
js// jQuery $el.html(); // Nativo el.innerHTML;Establecer HTML
js// jQuery $el.html(htmlString); // Nativo el.innerHTML = htmlString;
3.4 Añadir al final
Añadir elemento hijo después del último hijo del elemento padre
js// jQuery $el.append('Hello World'); // Nativo (string de HTML) el.insertAdjacentHTML('beforeend', 'Hello World'); // Nativo (Elemento) el.appendChild(newEl);3.5 Añadir al inicio
js// jQuery $el.prepend('Hello World'); // Nativo (String HTML) el.insertAdjacentHTML('afterbegin', 'Hello World'); // Nativo (Elemento) el.insertBefore(newEl, el.firstChild);3.6 Insertar Antes
Insertar un nuevo nodo antes de los elementos seleccionados
js// jQuery $newEl.insertBefore(selector); // Nativo (String HTML) el.insertAdjacentHTML('beforebegin ', 'Hello World'); // Native (Elemento) const el = document.querySelector(selector); if (el.parentNode) { el.parentNode.insertBefore(newEl, el); }3.7 Insertar después
Insertar un nuevo nodo después de los elementos seleccionados
js// jQuery $newEl.insertAfter(selector); // Nativo (String HTML) el.insertAdjacentHTML('afterend', 'Hello World'); // Nativo (Elemento) const el = document.querySelector(selector); if (el.parentNode) { el.parentNode.insertBefore(newEl, el.nextSibling); }3.8 es
Retorna
truesi coincide con el selector de la búsquedajs// jQuery - Nota `is` también funciona con `funciones` o `elementos` que no veremos aquí $el.is(selector); // Nativo el.matches(selector);3.9 Clonar
Crea una copia profunda del elemento
js// jQuery $el.clone(); // Nativo el.cloneNode(); // Para hacer copia profunda , establece como parametro `true`3.10 Vaciar
Elimina todos los nodos hijo
js// jQuery $el.empty(); // Nativo el.innerHTML = '';3.11 Envolver
Crea una estructura HTML alrededor de cada elemento
js// jQuery $('.inner').wrap(''); // Nativo Array.prototype.forEach.call(document.querySelectorAll('.inner'), (el) => { const wrapper = document.createElement('div'); wrapper.className = 'wrapper'; el.parentNode.insertBefore(wrapper, el); el.parentNode.removeChild(el); wrapper.appendChild(el); });3.12 Desenvolver
Elimina los padres de una serie de elementos seleccionados del DOM
js// jQuery $('.inner').unwrap(); // Nativo Array.prototype.forEach.call(document.querySelectorAll('.inner'), (el) => { Array.prototype.forEach.call(el.childNodes, (child) => { el.parentNode.insertBefore(child, el); }); el.parentNode.removeChild(el); });3.13 Remplazar con
Remplaza cada elemento en una serie de elementos seleccionados con nuevo contenido.
js// jQuery $('.inner').replaceWith(''); // Nativo Array.prototype.forEach.call(document.querySelectorAll('.inner'), (el) => { const outer = document.createElement('div'); outer.className = 'outer'; el.parentNode.insertBefore(outer, el); el.parentNode.removeChild(el); });
Ajax
+Fetch API es el nuevo estándar que reemplaza a XMLHttpRequest para efectuar peticiones AJAX. Funciona en Chrome y Firefox, como también es posible usar un polyfill en otros navegadores.
Es una buena alternativa utilizar github/fetch en IE9+ o fetch-ie8 en IE8+, fetch-jsonp para efectuar peticiones JSONP.
4.1 Carga datos desde un servidor y coloca el HTML regresado en el elemento seleccionado.
js// jQuery $(selector).load(url, completeCallback) // Nativo fetch(url).then(data => data.text()).then(data => { document.querySelector(selector).innerHTML = data }).then(completeCallback)
Eventos
Para un reemplazo completo con namespace y delegación, utilizar https://github.com/oneuijs/oui-dom-events
5.0 Document ready by
DOMContentLoadedjs// jQuery $(document).ready(eventHandler); // Nativo // Verifica que DOMContentLoaded ya se ha completado if (document.readyState !== 'loading') { eventHandler(); } else { document.addEventListener('DOMContentLoaded', eventHandler); }5.1 Asignar un evento con "on"
js// jQuery $el.on(eventName, eventHandler); // Nativo el.addEventListener(eventName, eventHandler);5.2 Desasignar un evento con "off"
js// jQuery $el.off(eventName, eventHandler); // Nativo el.removeEventListener(eventName, eventHandler);5.3 Trigger
js// jQuery $(el).trigger('custom-event', {key1: 'data'}); // Nativo if (window.CustomEvent) { const event = new CustomEvent('custom-event', {detail: {key1: 'data'}}); } else { const event = document.createEvent('CustomEvent'); event.initCustomEvent('custom-event', true, true, {key1: 'data'}); } el.dispatchEvent(event);
Utilidades
La mayoría de las utilidades se encuentran en la API nativa. Otras funciones avanzadas podrían por utilidades de librerías que se centran en la consistencia y rendimiento. Se recomienda lodash como replazo.
6.1 Utilidades Básicas
- isArray
Determina si el lemento es un vector(array).
js// jQuery $.isArray(array); // Nativo Array.isArray(array);- isWindow
Determina si el argumento en una ventana(window).
js// jQuery $.isWindow(obj); // Nativo function isWindow(obj) { return obj !== null && obj !== undefined && obj === obj.window; }- inArray
Busca un valor específico en el array y retorna su índice (o -1 si no lo encuentra).
js// jQuery $.inArray(item, array); // Nativo array.indexOf(item) > -1; // ES6 array.includes(item);- isNumeric
Determina si el argumento es un número.
Utilizatypeofpara decidir el tipo deltypeejemplo para mayor precisión.js// jQuery $.isNumeric(item); // Nativo function isNumeric(value) { var type = typeof value; return (type === 'number' || type === 'string') && !Number.isNaN(value - Number.parseFloat(value)); }- isFunction
Determina si el argumento es objecto función de Javascript.
js// jQuery $.isFunction(item); // Nativo function isFunction(item) { if (typeof item === 'function') { return true; } var type = Object.prototype.toString(item); return type === '[object Function]' || type === '[object GeneratorFunction]'; }- isEmptyObject
Verifica que un objeto esté vacío(contiene propiedades no enumerables).
js// jQuery $.isEmptyObject(obj); // Nativo function isEmptyObject(obj) { return Object.keys(obj).length === 0; }- isPlainObject
Verifica si un objeto es un objeto plano (creado utilizando “{}” o “new Object”).
js// jQuery $.isPlainObject(obj); // Nativo function isPlainObject(obj) { if (typeof (obj) !== 'object' || obj.nodeType || obj !== null && obj !== undefined && obj === obj.window) { return false; } if (obj.constructor && !Object.prototype.hasOwnProperty.call(obj.constructor.prototype, 'isPrototypeOf')) { return false; } return true; }- extend
Combina los contenidos de dos o mas objetos en el primer objeto.
object.assign es una API de ES6, puedes utilizar polyfill también.js// jQuery $.extend({}, defaultOpts, opts); // Nativo Object.assign({}, defaultOpts, opts);- trim
Elimina los espacios en blanco del inicio y final de un string.
js// jQuery $.trim(string); // Nativo string.trim();- map
Traslada todos los elementos en un arreglo u objeto a un nuevo arreglo de elementos.
js// jQuery $.map(array, (value, index) => { }); // Nativo array.map((value, index) => { });- each
Una función genérica de iteración, que puede ser utilizada de manera similar para iterar en objetos o arreglos.
js// jQuery $.each(array, (index, value) => { }); // Nativo array.forEach((value, index) => { });- grep
Encuentra los elementos de un arreglo que satisfacen una función filtro.
js// jQuery $.grep(array, (value, index) => { }); // Nativo array.filter((value, index) => { });- type
Determina la clase [Class] interna de Javascript de un objeto.
js// jQuery $.type(obj); // Nativo function type(item) { const reTypeOf = /(?:^\[object\s(.*?)\]$)/; return Object.prototype.toString.call(item) .replace(reTypeOf, '$1') .toLowerCase(); }- merge
Combina los contenidos de dos o mas arreglos en el primero.
js// jQuery $.merge(array1, array2); // Nativo // Pero la función concat no elimina elementos duplicados. function merge(...args) { return [].concat(...args) }- now
Retorna un número que representa la hora actual.
js// jQuery $.now(); // Native Date.now();- proxy
Toma una función y regresa una nueva que siempre tendrá un contexto particular.
js// jQuery $.proxy(fn, context); // Nativo fn.bind(context);- makeArray
Convierte un objeto similar a un arreglo en un verdarero arreglo de Javascript.
js// jQuery $.makeArray(arrayLike); // Nativo Array.prototype.slice.call(arrayLike); // ES6 Array.from(arrayLike);6.2 Contenedores
Verifica si un elemento del DOM es descendiente de otro elemento del DOM.
js// jQuery $.contains(el, child); // Nativo el !== child && el.contains(child);6.3 Globaleval
Ejecuta el mismo código Javascript de manera global.
js// jQuery $.globaleval(code); // Nativo function Globaleval(code) { const script = document.createElement('script'); script.text = code; document.head.appendChild(script).parentNode.removeChild(script); } // Utilzando eval, pero el contexto de eval es el actual, el contexto de $.Globaleval es global. eval(code);6.4 parse
- parseHTML
Parsea un string ien un arreglo de nodos DOM.
js// jQuery $.parseHTML(htmlString); // Nativo function parseHTML(string) { const context = document.implementation.createHTMLDocument(); // Se establece la base href para el documento creado, así todos los elementos parseados con URLs // estarán basados en ña URL del documento const base = context.createElement('base'); base.href = document.location.href; context.head.appendChild(base); context.body.innerHTML = string; return context.body.children; }- parseJSON
Toma un string de JSON bien formado y retorna el valor resultante de Javascript.
js// jQuery $.parseJSON(str); // Native JSON.parse(str);
Promesas
Una promesa, representa el resultado eventual de una operación asíncrona. jQuery tiene su propio sistema para utilizar promesas. JavaScript nativo implementa una ligera y mínima API para utilizar promesas de acuerdo con la especificación Promises/A+.
7.1 done, fail, always
donese llama cuando una promesa se resuelve,failse llama cuando una promesa es rechazada,alwaysse llama cuando una promesa no ha sido resuelta o rechazada.js// jQuery $promise.done(doneCallback).fail(failCallback).always(alwaysCallback) // Nativo promise.then(doneCallback, failCallback).then(alwaysCallback, alwaysCallback)7.2 when
whense utiliza para manipular múltiples promesas. Se resolverá cuando todas las promesas sean resueltas y se rechazará si alguna es rechazada.js// jQuery $.when($promise1, $promise2).done((promise1Result, promise2Result) => { }); // Nativo Promise.all([$promise1, $promise2]).then([promise1Result, promise2Result] => {});7.3 Deferred
Deferred es una manera de crear promesas.
js// jQuery function asyncFunc() { const defer = new $.Deferred(); setTimeout(() => { if(true) { defer.resolve('some_value_computed_asynchronously'); } else { defer.reject('failed'); } }, 1000); return defer.promise(); } // Nativo function asyncFunc() { return new Promise((resolve, reject) => { setTimeout(() => { if (true) { resolve('some_value_computed_asynchronously'); } else { reject('failed'); } }, 1000); }); } // Deferred function defer() { const deferred = {}; const promise = new Promise((resolve, reject) => { deferred.resolve = resolve; deferred.reject = reject; }); deferred.promise = () => { return promise; }; return deferred; } function asyncFunc() { const defer = defer(); setTimeout(() => { if(true) { defer.resolve('some_value_computed_asynchronously'); } else { defer.reject('failed'); } }, 1000); return defer.promise(); }
Animaciones
8.1 Mostrar y ocultar
js// jQuery $el.show(); $el.hide(); // Native // Para mas detalles acerca del método show, refierase a https://github.com/oneuijs/oui-dom-utils/blob/master/src/index.js#L363 el.style.display = ''|'inline'|'inline-block'|'inline-table'|'block'; el.style.display = 'none';8.2 Toggle
Muestra u oculta el elemento
js// jQuery $el.toggle(); // Nativo if (el.ownerDocument.defaultView.getComputedStyle(el, null).display === 'none') { el.style.display = ''|'inline'|'inline-block'|'inline-table'|'block'; } else { el.style.display = 'none'; }8.3 FadeIn & FadeOut
js// jQuery $el.fadeIn(3000); $el.fadeOut(3000); // Nativo el.style.transition = 'opacity 3s'; // fadeIn el.style.opacity = '1'; // fadeOut el.style.opacity = '0';8.4 FadeTo
Ajusta la opacidad del elemento
js// jQuery $el.fadeTo('slow',0.15); // Nativo el.style.transition = 'opacity 3s'; // assume 'slow' equals 3 seconds el.style.opacity = '0.15';8.5 FadeToggle
Muestra u oculta el emento animando su opacidad.
js// jQuery $el.fadeToggle(); // Nativo el.style.transition = 'opacity 3s'; const { opacity } = el.ownerDocument.defaultView.getComputedStyle(el, null); if (opacity === '1') { el.style.opacity = '0'; } else { el.style.opacity = '1'; }8.6 SlideUp & SlideDown
js// jQuery $el.slideUp(); $el.slideDown(); // Nativo const originHeight = '100px'; el.style.transition = 'height 3s'; // slideUp el.style.height = '0px'; // slideDown el.style.height = originHeight;8.7 SlideToggle
Muestra u oculta el elemento con una animación de deslizamiento.
js// jQuery $el.slideToggle(); // Nativo const originHeight = '100px'; el.style.transition = 'height 3s'; const { height } = el.ownerDocument.defaultView.getComputedStyle(el, null); if (parseInt(height, 10) === 0) { el.style.height = originHeight; } else { el.style.height = '0px'; }8.8 Animate
Realiza una animación personalizada de un conjunto de propiedades CSS.
js// jQuery $el.animate({ params }, speed); // Nativo el.style.transition = 'all ' + speed; Object.keys(params).forEach((key) => { el.style[key] = params[key]; });
Alternativas
- Quizá no necesites jQuery - Ejemplos de como hacer un evento común, un elemento, ajax, etc, con Javascript puro.
- npm-dom y webmodules - Organizaciones en las puedes encontrar módulos individuales del DOM en NPM.
Navegadores soportados
![]() |
![]() |
![]() |
![]() |
![]() |
|---|---|---|---|---|
| Última ✔ | Última ✔ | 10+ ✔ | Última ✔ | 6.1+ ✔ |
Licencia
MIT
File: README-fr.md
Vous n'avez pas besoin de jQuery
De nos jours, les environnements frontend évoluent si rapidement que les navigateurs récents ont déjà implémenté beaucoup d'API DOM/BOM suffisantes. Il n'est pas utile d'apprendre jQuery à partir de rien pour manipuler le DOM ou les évènements. Pendant ce temps, grâce à l'efficacité de bibliothèques frontend comme React, Angular et Vue, manipuler directement le DOM est devenu obsolète, jQuery n'a jamais été aussi peu important. Ce projet résume la plupart des alternatives à jQuery à l'aide d'implémentations natives, compatibles avec IE 10+.
Sommaire
- Traductions
- Sélecteur jQuery
- Style et CSS
- Manipulation du DOM
- Ajax
- Évènements
- Utilitaires
- Promesses
- Animation
- Alternatives
- Navigateurs compatibles
Traductions
- 한국어
- 正體中文
- 简体中文
- Bahasa Melayu
- Bahasa Indonesia
- Português(PT-BR)
- Tiếng Việt Nam
- Español
- Русский
- Кыргызча
- Türkçe
- Italiano
- Français
- 日本語
- Polski
Sélecteur jQuery
À la place des sélecteurs communs comme class, id ou attribute il est possible d'utiliser document.querySelector ou document.querySelectorAll. Les différences sont que:
document.querySelectorretourne le premier élément trouvé,document.querySelectorAllretourne tous les éléments trouvés sous forme d'une NodeList. Il est possible de le convertir en Array à l'aide de[].slice.call(document.querySelectorAll(selector) || []);,- si aucun élément n'a été trouvé, jQuery peut retourner
[]alors que l'API DOM va retournernull. Faites attention au Null Pointer Exception. Vous pouvez aussi utiliser||pour définir la valeur par défaut si rien n'a été trouvé, commedocument.querySelectorAll(selector) || [].
Remarque:
document.querySelectoretdocument.querySelectorAllsont assez LENTS, essayez plutôt d'utilisergetElementById,document.getElementsByClassNameoudocument.getElementsByTagNamesi vous souhaitez obtenir un gain de performance.
1.0 Requête par sélecteur
js// jQuery $('selector'); // Natif document.querySelectorAll('selector');1.1 Requête par classe
js// jQuery $('.class'); // Natif document.querySelectorAll('.class'); // ou document.getElementsByClassName('class');1.2 Requête par id
js// jQuery $('#id'); // Natif document.querySelector('#id'); // ou document.getElementById('id');1.3 Requête par attribut
js// jQuery $('a[target=_blank]'); // Natif document.querySelectorAll('a[target=_blank]');1.4 Requête par descendants
js// jQuery $el.find('li'); // Natif el.querySelectorAll('li');1.5 Éléments voisins/précédents/suivants
Éléments voisins
js// jQuery $el.siblings(); // Natif [].filter.call(el.parentNode.children, function(child) { return child !== el; });Éléments précédents
js// jQuery $el.prev(); // Natif el.previousElementSibling;Éléments suivants
js// next $el.next(); el.nextElementSibling;
1.6 Plus proche
Retourne le premier élément trouvé à l'aide du sélecteur fourni, parcourant l'élément actuel vers le document.
js// jQuery $el.closest(queryString); // Natif - Seulement le dernier, ne fonctionne pas sous IE el.closest(selector); // Natif - 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 jusqu'à
Retourne les ancêtres de chaque élément dans l'ensemble d'éléments trouvés courants, jusqu'à (sans l'inclure) l'élément correspondant au sélecteur, le noeud DOM ou l'objet JQuery.
js// jQuery $el.parentsUntil(selector, filter); // Natif function parentsUntil(el, selector, filter) { const result = []; const matchesSelector = el.matches || el.webkitMatchesSelector || el.mozMatchesSelector || el.msMatchesSelector; // la correspondance commence à partir du 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 Formulaire
Input/Textarea
js// jQuery $('#my-input').val(); // Natif document.querySelector('#my-input').value;Obtenir l'index du e.currentTarget entre
.radiojs// jQuery $(e.currentTarget).index('.radio'); // Natif [].indexOf.call(document.querySelectorAll('.radio'), e.currentTarget);
1.9 Contenus Iframe
$('iframe').contents()retournecontentDocumentpour cet iframe en particulierContenus de l'Iframe
js// jQuery $iframe.contents(); // Natif iframe.contentDocument;Requête Iframe
js// jQuery $iframe.contents().find('.css'); // Natif iframe.contentDocument.querySelectorAll('.css');
Style & CSS
2.1 CSS
Obtenir le style
js// jQuery $el.css("color"); // Natif // NOTE: Bug connu, retournera 'auto" si la valeur du site est 'auto' const win = el.ownerDocument.defaultView; // null signifie ne pas retourner les pseudo styles win.getComputedStyle(el, null).color;Définir le style
js// jQuery $el.css({ color: "#ff0011" }); // Natif el.style.color = '#ff0011';Obtenir/Définir les styles
Notez que si vous souhaitez définir plusieurs styles à la fois, you devriez vous référer à la méthode setStyles du paquet oui-dom-utils.
Ajouter une classe
js// jQuery $el.addClass(className); // Natif el.classList.add(className);Supprimer une classe
js// jQuery $el.removeClass(className); // Natif el.classList.remove(className);Possède une classe
js// jQuery $el.hasClass(className); // Natif el.classList.contains(className);Basculer une class
js// jQuery $el.toggleClass(className); // Natif el.classList.toggle(className);
2.2 Largeur et Hauteur
Travailler avec la hauteur ou la largeur est en théorie identique, prenons la hauteur pour exemple:
Hauteur de la fenêtre
js// hauteur de la fenêtre $(window).height(); // se comporte comme jQuery sans ascenseur window.document.documentElement.clientHeight; // avec ascenseur window.innerHeight;Hauteur du document
js// jQuery $(document).height(); // Natif document.documentElement.scrollHeight;Hauteur de l'élement
js// jQuery $el.height(); // NatiF 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; } // précis à l'entier près (quand `border-box`, son `height - border`; quand `content-box`, son `height + padding`) el.clientHeight; // précis à la décimale près (quand `border-box`, son `height`; quand `content-box`, son `height + padding + border`) el.getBoundingClientRect().height;
2.3 Position et offset
Position
Récupère les coordonnées courantes de l'élement relatif à l'offset parent.
js// jQuery $el.position(); // Natif { left: el.offsetLeft, top: el.offsetTop }Offset
Récupère les coordonnées courantes de l'élement relatif au document.
js// jQuery $el.offset(); // Natif 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 Défiler vers le haut
Récupère la position verticale courante de l'ascenseur pour cet élément.
js// jQuery $(window).scrollTop(); // Natif (document.documentElement && document.documentElement.scrollTop) || document.body.scrollTop;
Manipulation du DOM
3.1 Supprimer
Supprime l'élément du DOM.
js// jQuery $el.remove(); // Natif el.parentNode.removeChild(el);3.2 Texte
Obtenir le texte
Récupère le contenu textuel combiné de l'élément en incluant ses descendants.
js// jQuery $el.text(); // Natif el.textContent;Définir le text
Définit le contenu de l'élément à partir du texte spécifié.
js// jQuery $el.text(string); // Natif el.textContent = string;
3.3 HTML
Obtenir l'HTML
js// jQuery $el.html(); // Natif el.innerHTML;Définir l'HTML
js// jQuery $el.html(htmlString); // Natif el.innerHTML = htmlString;
3.4 Ajouter
Ajouter un élément enfant après le dernier enfant de l'élément parent.
js// jQuery $el.append("hello"); // Natif let newEl = document.createElement('div'); newEl.setAttribute('id', 'container'); newEl.innerHTML = 'hello'; el.appendChild(newEl);3.5 Faire précéder
js// jQuery $el.prepend("hello"); // Natif let newEl = document.createElement('div'); newEl.setAttribute('id', 'container'); newEl.innerHTML = 'hello'; el.insertBefore(newEl, el.firstChild);3.6 Insérer avant
Insérer un nouveau noeud avant les éléments sélectionnés.
js// jQuery $newEl.insertBefore(queryString); // Natif newEl.insertBefore(document.querySelector(queryString));3.7 Insérer après
Insérer un nouveau noeud après les noeuds sélectionnés
js// jQuery $newEl.insertAfter(queryString); // Natif function insertAfter(newEl, queryString) { const parent = document.querySelector(queryString).parentNode; if (parent.lastChild === newEl) { parent.appendChild(newEl); } else { parent.insertBefore(newEl, parent.nextSibling); } },3.8 est
Retourne
truele paramètre correspond à la requête de sélectionjs// jQuert - Noter que `is` fonctionne également avec `function` ou `elements` qui ne sont pas concernés ici $el.is(selector); // Natif el.matches(selector);3.9 clone
Créé une copie profonde de cet élément
js// jQuery $el.clone(); // Natif el.cloneNode(); // Pour une copie profonde, définir le paramètre à `true`3.10 vider
Supprime tous les noeuds enfants
js// jQuery $el.empty(); // Natif el.innerHTML = '';3.11 enrouler
Enrouler une structure HTML autour de chaque élément
js// jQuery $('.inner').wrap(''); // Natif [].slice.call(document.querySelectorAll('.inner')).forEach(function(el){ var wrapper = document.createElement('div'); wrapper.className = 'wrapper'; el.parentNode.insertBefore(wrapper, el); el.parentNode.removeChild(el); wrapper.appendChild(el); });3.12 dérouler
Supprime les parents de la collection des éléments correspondants du DOM
js// jQuery $('.inner').unwrap(); // Natif [].slice.call(document.querySelectorAll('.inner')).forEach(function(el){ [].slice.call(el.childNodes).forEach(function(child){ el.parentNode.insertBefore(child, el); }); el.parentNode.removeChild(el); });
Ajax
Fetch API est le nouveau standard qui a pour but de remplacer XMLHttpRequest afin de faire de l'ajax. Il fonctionne sous Chrome et Firefox, il est possible d'utiliser polyfills pour le faire fonctionner sur de vieux navigateurs.
Essayer github/fetch sous IE9+ ou fetch-ie8 sous IE8+, fetch-jsonp pour construire des requêtes JSONP.
Évènements
Pour remplacer complètement jusqu'aux espaces de nom et délégations, se référer à https://github.com/oneuijs/oui-dom-events
5.1 Attacher un événement avec
onjs// jQuery $el.on(eventName, eventHandler); // Natif el.addEventListener(eventName, eventHandler);5.2 Détacher un événement avec
offjs// jQuery $el.off(eventName, eventHandler); // Natif el.removeEventListener(eventName, eventHandler);5.3 Trigger
js// jQuery $(el).trigger('custom-event', {key1: 'data'}); // Natif if (window.CustomEvent) { const event = new CustomEvent('custom-event', {detail: {key1: 'data'}}); } else { const event = document.createEvent('CustomEvent'); event.initCustomEvent('custom-event', true, true, {key1: 'data'}); } el.dispatchEvent(event);
Utilitaires
La plupart des utilitaires se trouvent dans l'API native. D'autres fonctions avancées peuvent être choisies afin de se concentrer sur la cohérence et la performance. Il est recommandé de remplacer par lodash.
6.1 Utilitaires basiques
- isArray
Détermine si l'argument est un tableau.
js// jQuery $.isArray(range); // Natif Array.isArray(range);- isWindow
Détermine si l'argument est une fenêtre.
js// jQuery $.isWindow(obj); // Native function isWindow(obj) { return obj != null && obj === obj.window; }- inArray
Recherche une valeur spécifique à l'intérieur d'un tableau et retourne son index (ou -1 si rien n'a été trouvé).
js// jQuery $.inArray(item, array); // Natif Array.indexOf(item);- isNumeric
Détermine si l'argument est un nombre.
Utilisertypeofpour décider du type. Si nécessaire utiliser une bibliothèque, parfoistypeofn'est pas exact.js// jQuery $.isNumeric(item); // Natif function isNumeric(item) { return typeof item === 'number'; }- isFunction
Détermine si l'argument est un objet fonction JavaScript.
js// jQuery $.isFunction(item); // Natif function isFunction(item) { return typeof value === 'function'; }- isEmptyObject
Vérifie si un objet est vide (ne contient aucune propriétés énumérables).
js// jQuery $.isEmptyObject(obj); // Natif function isEmptyObject(obj) { for (let key in obj) { return false; } return true; }- isPlainObject
Vérifie si un objet est un objet "plat" (créé en utilisant "{}" ou "new Object").
js// jQuery $.isPlainObject(obj); // Natif function isPlainObject(obj) { if (typeof (obj) !== 'object' || obj.nodeType || obj != null && obj === obj.window) { return false; } if (obj.constructor && !{}.hasOwnProperty.call(obj.constructor.prototype, 'isPrototypeOf')) { return false; } return true; }- extend
Fusionne le contenu de deux objets ou plus ensembles en un seul objet.
Object.assign fait parti de l'API ES6, il est également possible d'utiliser polyfill.js// jQuery $.extend({}, defaultOpts, opts); // Natif Object.assign({}, defaultOpts, opts);- trim
Supprime les espaces au début et à la fin d'une chaine de caractères String.
js// jQuery $.trim(string); // Natif string.trim();- map
Traduit tous les éléments d'un tableau ou d'un objet vers un nouveau tableau d'éléments.
js// jQuery $.map(array, function(value, index) { }); // Natif array.map(function(value, index) { });- each
Une fonction générique d'itération, qui peut être utilisée pour itérer de façon transparente à travers des objets et des tableaux.
js// jQuery $.each(array, function(value, index) { }); // Natif array.forEach(function(value, index) { });- grep
Trouve les éléments d'un tableau qui satisfont avec une fonction filtre.
js// jQuery $.grep(array, function(value, index) { }); // Natif array.filter(function(value, index) { });- type
Détermine la [[Class]] interne JavaScript d'un objet.
js// jQuery $.type(obj); // Natif Object.prototype.toString.call(obj).replace(/^\[object (.+)\]$/, '$1').toLowerCase();- merge
Fusionne le contenu de deux tableau dans un seul tableau.
js// jQuery $.merge(array1, array2); // Natif // But concat function don't remove duplicate items. function merge() { return Array.prototype.concat.apply([], arguments) }- now
Retourne un nombre représentant l'heure actuelle.
js// jQuery $.now(); // Natif Date.now();- proxy
Prend une fonction et en retourne une nouvelle qui aura toujours un contexte particulier.
js// jQuery $.proxy(fn, context); // Natif fn.bind(context);- makeArray
Convertit un objet "array-like" vers un véritable tableau JavaScript.
js// jQuery $.makeArray(array); // Natif [].slice.call(array);6.2 Contient
Vérifie si un élément du DOM est un descendant d'un autre élément du DOM.
js// jQuery $.contains(el, child); // Natif el !== child && el.contains(child);6.3 Globaleval
Exécute du code JavaScript de manière globale.
js// jQuery $.globaleval(code); // Natif function Globaleval(code) { let script = document.createElement('script'); script.text = code; document.head.appendChild(script).parentNode.removeChild(script); } // Utilise eval, mais le contexte d'eval est l'actuel alors que le contexte de $.Globaleval est global. eval(code);6.4 parse
- parseHTML
Parse une chaine de caractères vers un tableau de noeuds DOM.
js// jQuery $.parseHTML(htmlString); // Natif function parseHTML(string) { const tmp = document.implementation.createHTMLDocument(); tmp.body.innerHTML = string; return tmp.body.children; }- parseJSON
Prend une chaine JSON correctement formatée et retourne la valeur JavaScript résultante.
js// jQuery $.parseJSON(str); // Natif JSON.parse(str);
Promesses
Une promesse représente le résultat éventuel d'une opération asynchrone. jQuery a sa propre manière de traiter les promesses. JavaScript natif implémente une API minimale et légère afin de traiter les promesses en accord avec les spécifications Promises/A+.
7.1 done, fail, always
doneest appelée quand une promesse est résolue,failest appelée quand une promesse est rejetée etalwaysest appelée quand une promesse n'est ni résolue ni rejetée.js// jQuery $promise.done(doneCallback).fail(failCallback).always(alwaysCallback) // Natif promise.then(doneCallback, failCallback).then(alwaysCallback, alwaysCallback)7.2 when
whenest utilisée pour traiter de multiples promesses. Elle sera résolue quand toutes les promesses le seront, and rejetée si au moins une est rejetée.js// jQuery $.when($promise1, $promise2).done((promise1Result, promise2Result) => {}) // Natif Promise.all([$promise1, $promise2]).then([promise1Result, promise2Result] => {});7.3 Deferred
Deferred est un moyen de créer une promesse.
js// jQuery function asyncFunc() { var d = new $.Deferred(); setTimeout(function() { if(true) { d.resolve('some_value_compute_asynchronously'); } else { d.reject('failed'); } }, 1000); return d.promise(); } // Natif function asyncFunc() { return new Promise((resolve, reject) => { setTimeout(function() { if (true) { resolve('some_value_compute_asynchronously'); } else { reject('failed'); } }, 1000); }); } // Avec deferred function defer() { let resolve, reject; let promise = new Promise(function() { resolve = arguments[0]; reject = arguments[1]; }); return { resolve, reject, promise }; } function asyncFunc() { var d = defer(); setTimeout(function() { if(true) { d.resolve('some_value_compute_asynchronously'); } else { d.reject('failed'); } }, 1000); return d.promise; }
Animation
8.1 Show & Hide
js// jQuery $el.show(); $el.hide(); // Natif //Pour plus de détails à propos de la méthode show, merci de se référer à https://github.com/oneuijs/oui-dom-utils/blob/master/src/index.js#L363 el.style.display = ''|'inline'|'inline-block'|'inline-table'|'block'; el.style.display = 'none';8.2 Toggle
Affiche ou cache un élément.
js// jQuery $el.toggle(); // Natif if (el.ownerDocument.defaultView.getComputedStyle(el, null).display === 'none') { el.style.display = ''|'inline'|'inline-block'|'inline-table'|'block'; } else { el.style.display = 'none'; }8.3 FadeIn & FadeOut
js// jQuery $el.fadeIn(3000); $el.fadeOut(3000); // Natif el.style.transition = 'opacity 3s'; // fadeIn el.style.opacity = '1'; // fadeOut el.style.opacity = '0';8.4 FadeTo
Ajuste l'opacité d'un élément.
js// jQuery $el.fadeTo('slow',0.15); // Natif el.style.transition = 'opacity 3s'; // assume que 'slow' vaut 3 seconds el.style.opacity = '0.15';8.5 FadeToggle
Affiche ou cache un élément en animant son opacité.
js// jQuery $el.fadeToggle(); // Natif el.style.transition = 'opacity 3s'; let { opacity } = el.ownerDocument.defaultView.getComputedStyle(el, null); if (opacity === '1') { el.style.opacity = '0'; } else { el.style.opacity = '1'; }8.6 SlideUp & SlideDown
js// jQuery $el.slideUp(); $el.slideDown(); // Natif let originHeight = '100px'; el.style.transition = 'height 3s'; // slideUp el.style.height = '0px'; // slideDown el.style.height = originHeight;8.7 SlideToggle
Affiche ou cache un élément en le faisant glisser.
js// jQuery $el.slideToggle(); // Natif let originHeight = '100px'; el.style.transition = 'height 3s'; let { height } = el.ownerDocument.defaultView.getComputedStyle(el, null); if (parseInt(height, 10) === 0) { el.style.height = originHeight; } else { el.style.height = '0px'; }8.8 Animate
Réalise une animation personnaliée à partir d'une collection de propriétés CSS.
js// jQuery $el.animate({params}, speed); // Natif el.style.transition = 'all' + speed; Object.keys(params).forEach(function(key) { el.style[key] = params[key]; })
Alternatives
- You Might Not Need jQuery - Des exemples sur comment faire un simple évènement, ajax etc avec du javascript pur.
- npm-dom et webmodules - Modules DOM sur NPM.
Traductions
- 한국어
- 简体中文
- Bahasa Melayu
- Bahasa Indonesia
- Português(PT-BR)
- Tiếng Việt Nam
- Español
- Русский
- Türkçe
- Italian
- Français
Navigateurs compatibles
| | | |
--- | --- | --- | --- | --- |
Plus récente ✔ | Plus récente ✔ | 10+ ✔ | Plus récente ✔ | 6.1+ ✔ |
Licence
MIT
File: README-id.md
Anda tidak memerlukan jQuery
Perkembangan environment frontend sangatlah pesat, dimana banyak browser sudah mengimplementasikan DOM/BOM APIs dengan baik. Kita tidak perlu lagi belajar jQuery dari nol untuk keperluan memanipulasi DOM atau events. Secara bersamaan; dengan berterimakasih kepada library frontend terkini seperti React, Angular dan Vue; Memanipulasi DOM secara langsung telah menjadi anti-pattern atau sesuatu yang tidak perlu dilakukan lagi. Dengan kata lain, jQuery sekarang menjadi semakin tidak diperlukan. Projek ini memberikan informasi mengenai metode alternatif dari jQuery untuk implementasi Native dengan support untuk browser IE 10+.
Daftar Isi
Terjemahan
- 한국어
- 正體中文
- 简体中文
- Bahasa Melayu
- Bahasa Indonesia
- Português(PT-BR)
- Tiếng Việt Nam
- Español
- Русский
- Кыргызча
- Türkçe
- Italiano
- Français
- 日本語
- Polski
Query Selector
Untuk selector-selector umum seperti class, id atau attribute, kita dapat menggunakan document.querySelector atau document.querySelectorAll sebagai pengganti. Perbedaan diantaranya adalah:
document.querySelectormengembalikan elemen pertama yang cocokdocument.querySelectorAllmengembalikan semua elemen yang cocok sebagai NodeList. Hasilnya bisa dikonversikan menjadi Array[].slice.call(document.querySelectorAll(selector) || []);- Bila tidak ada hasil balik pada elemen yang cocok, jQuery akan mengembalikan
[]sedangkan DOM API akan mengembalikannull. Mohon diperhatikan mengenai Null Pointer Exception. Anda juga bisa menggunakan operator||untuk set nilai awal jika hasil pencarian tidak ditemukan :document.querySelectorAll(selector) || []
Perhatian:
document.querySelectordandocument.querySelectorAllsedikit LAMBAT. Silahkan menggunakangetElementById,document.getElementsByClassNameataudocument.getElementsByTagNamejika anda menginginkan tambahan performa.
1.0 Query by selector
js// jQuery $('selector'); // Native document.querySelectorAll('selector');1.1 Query by class
js// jQuery $('.class'); // Native document.querySelectorAll('.class'); // or document.getElementsByClassName('class');1.2 Query by id
js// jQuery $('#id'); // Native document.querySelector('#id'); // or document.getElementById('id');1.3 Query menggunakan attribute
js// jQuery $('a[target=_blank]'); // Native document.querySelectorAll('a[target=_blank]');1.4 Pencarian.
Mencari nodes
js// jQuery $el.find('li'); // Native el.querySelectorAll('li');Mencari body
js// jQuery $('body'); // Native document.body;Mencari Attribute
js// jQuery $el.attr('foo'); // Native e.getAttribute('foo');Mencari data attribute
js// jQuery $el.data('foo'); // Native // gunakan getAttribute el.getAttribute('data-foo'); // anda juga bisa menggunakan `dataset` bila anda perlu support IE 11+ el.dataset['foo'];
1.5 Elemen-elemen Sibling/Previous/Next
Elemen Sibling
js// jQuery $el.siblings(); // Native [].filter.call(el.parentNode.children, function(child) { return child !== el; });Elemen Previous
js// jQuery $el.prev(); // Native el.previousElementSibling;Elemen Next
js// next $el.next(); el.nextElementSibling;
1.6 Closest
Mengembalikan elemen sama yang digunakan dari selector pertama, dengan cara mencari elemen-sekarang sampai ke document.
js// jQuery $el.closest(queryString); // Native 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
Digunakan untuk mendapatkan "ancestor" dari setiap elemen yang ditemukan. Namun tidak termasuk elemen-sekarang yang sudah didapat dari pencarian oleh selector, DOM node, atau object jQuery.
js// 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
js// jQuery $('#my-input').val(); // Native document.querySelector('#my-input').value;Get index of e.currentTarget between
.radiojs// jQuery $(e.currentTarget).index('.radio'); // Native [].indexOf.call(document.querySelectAll('.radio'), e.currentTarget);
1.9 Iframe Contents
$('iframe').contents()mengembalikancontentDocumentIframe contents
js// jQuery $iframe.contents(); // Native iframe.contentDocument;Iframe Query
js// jQuery $iframe.contents().find('.css'); // Native iframe.contentDocument.querySelectorAll('.css');
CSS Style
2.1 CSS
Get style
js// jQuery $el.css("color"); // Native // PERHATIAN: ada bug disini, dimana fungsi ini akan mengembalikan nilai 'auto' bila nilai dari atribut style adalah 'auto' const win = el.ownerDocument.defaultView; // null artinya tidak mengembalikan pseudo styles win.getComputedStyle(el, null).color;Set style
js// jQuery $el.css({ color: "#ff0011" }); // Native el.style.color = '#ff0011';Get/Set Styles
Mohon dicatat jika anda ingin mengubah style secara bersamaan, anda dapat menemukan referensi di metode setStyles pada package oui-dom-utils
Add class
js// jQuery $el.addClass(className); // Native el.classList.add(className);Remove class
js// jQuery $el.removeClass(className); // Native el.classList.remove(className);has class
js// jQuery $el.hasClass(className); // Native el.classList.contains(className);Toggle class
js// jQuery $el.toggleClass(className); // Native el.classList.toggle(className);
2.2 Width & Height
Secara teori, width dan height identik, contohnya Height:
Window height
js// window height $(window).height(); // without scrollbar, behaves like jQuery window.document.documentElement.clientHeight; // with scrollbar window.innerHeight;Document height
js// jQuery $(document).height(); // Native document.documentElement.scrollHeight;Element height
js// jQuery $el.height(); // Native function getHeight(el) { const styles = this.getComputedStyles(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
js// jQuery $el.position(); // Native { left: el.offsetLeft, top: el.offsetTop }Offset
js// 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
js// jQuery $(window).scrollTop(); // Native (document.documentElement && document.documentElement.scrollTop) || document.body.scrollTop;
DOM Manipulation
3.1 Remove
js// jQuery $el.remove(); // Native el.parentNode.removeChild(el);3.2 Text
Get text
js// jQuery $el.text(); // Native el.textContent;Set text
js// jQuery $el.text(string); // Native el.textContent = string;
3.3 HTML
Get HTML
js// jQuery $el.html(); // Native el.innerHTML;Set HTML
js// jQuery $el.html(htmlString); // Native el.innerHTML = htmlString;
3.4 Append
Menambahkan elemen-anak setelah anak terakhir dari elemen-parent
js// jQuery $el.append("hello"); // Native let newEl = document.createElement('div'); newEl.setAttribute('id', 'container'); newEl.innerHTML = 'hello'; el.appendChild(newEl);3.5 Prepend
js// jQuery $el.prepend("hello"); // Native let newEl = document.createElement('div'); newEl.setAttribute('id', 'container'); newEl.innerHTML = 'hello'; el.insertBefore(newEl, el.firstChild);3.6 insertBefore
Memasukkan node baru sebelum elemen yang dipilih.
js// jQuery $newEl.insertBefore(queryString); // Native const target = document.querySelector(queryString); target.parentNode.insertBefore(newEl, target);3.7 insertAfter
Memasukkan node baru sesudah elemen yang dipilih.
js// jQuery $newEl.insertAfter(queryString); // Native const target = document.querySelector(queryString); target.parentNode.insertBefore(newEl, target.nextSibling);
Ajax
Gantikan dengan fetch dan fetch-jsonp
Events
Untuk penggantian secara menyeluruh dengan namespace dan delegation, lihat ke https://github.com/oneuijs/oui-dom-events
5.1 Bind event dengan menggunakan on
js// jQuery $el.on(eventName, eventHandler); // Native el.addEventListener(eventName, eventHandler);5.2 Unbind event dengan menggunakan off
js// jQuery $el.off(eventName, eventHandler); // Native el.removeEventListener(eventName, eventHandler);5.3 Trigger
js// jQuery $(el).trigger('custom-event', {key1: 'data'}); // Native if (window.CustomEvent) { const event = new CustomEvent('custom-event', {detail: {key1: 'data'}}); } else { const event = document.createEvent('CustomEvent'); event.initCustomEvent('custom-event', true, true, {key1: 'data'}); } el.dispatchEvent(event);
Utilities
6.1 isArray
js// jQuery $.isArray(range); // Native Array.isArray(range);6.2 Trim
js// jQuery $.trim(string); // Native string.trim();6.3 Object Assign
Extend, use object.assign polyfill https://github.com/ljharb/object.assign
js// jQuery $.extend({}, defaultOpts, opts); // Native Object.assign({}, defaultOpts, opts);6.4 Contains
js// jQuery $.contains(el, child); // Native el !== child && el.contains(child);
Browser yang di Support
| | | |
--- | --- | --- | --- | --- |
Latest ✔ | Latest ✔ | 10+ ✔ | Latest ✔ | 6.1+ ✔ |
License
MIT
File: README-it.md
Non hai bisogno di jQuery
Il mondo del Frontend si evolve rapidamente oggigiorno, i browsers moderni hanno gia' implementato un'ampia gamma di DOM/BOM API soddisfacenti. Non dobbiamo imparare jQuery dalle fondamenta per la manipolazione del DOM o di eventi. Nel frattempo, grazie al prevalicare di librerie per il frontend come React, Angular a Vue, manipolare il DOM direttamente diventa un anti-pattern, di consequenza jQuery non e' mai stato meno importante. Questo progetto sommarizza la maggior parte dei metodi e implementazioni alternative a jQuery, con il supporto di IE 10+.
Tabella contenuti
- Traduzioni
- Query Selector
- CSS & Style
- Manipolazione DOM
- Ajax
- Eventi
- Utilities
- Alternative
- Supporto Browsers
Traduzioni
- 한국어
- 正體中文
- 简体中文
- Bahasa Melayu
- Bahasa Indonesia
- Português(PT-BR)
- Tiếng Việt Nam
- Español
- Русский
- Кыргызча
- Türkçe
- Italiano
- Français
- 日本語
- Polski
Query Selector
Al posto di comuni selettori come class, id o attributi possiamo usare document.querySelector o document.querySelectorAll per sostituzioni. La differenza risiede in:
document.querySelectorrestituisce il primo elemento combiaciantedocument.querySelectorAllrestituisce tutti gli elementi combiacianti della NodeList. Puo' essere convertito in Array usando[].slice.call(document.querySelectorAll(selector) || []);- Se nessun elemento combiacia, jQuery restituitirebbe
[]li' dove il DOM API ritornera'null. Prestate attenzione al Null Pointer Exception. Potete anche usare||per settare valori di default se non trovato, comedocument.querySelectorAll(selector) || []
Notare:
document.querySelectoredocument.querySelectorAllsono abbastanza SLOW, provate ad usaregetElementById,document.getElementsByClassNameodocument.getElementsByTagNamese volete avere un bonus in termini di performance.
1.0 Query da selettore
js// jQuery $('selector'); // Nativo document.querySelectorAll('selector');1.1 Query da classe
js// jQuery $('.class'); // Nativo document.querySelectorAll('.class'); // or document.getElementsByClassName('class');1.2 Query da id
js// jQuery $('#id'); // Nativo document.querySelector('#id'); // o document.getElementById('id');1.3 Query da attributo
js// jQuery $('a[target=_blank]'); // Nativo document.querySelectorAll('a[target=_blank]');1.4 Trovare qualcosa.
Trovare nodes
js// jQuery $el.find('li'); // Nativo el.querySelectorAll('li');Trovare body
js// jQuery $('body'); // Nativo document.body;Trovare Attributi
js// jQuery $el.attr('foo'); // Nativo e.getAttribute('foo');Trovare attributo data
js// jQuery $el.data('foo'); // Nativo // using getAttribute el.getAttribute('data-foo'); // potete usare `dataset` solo se supportate IE 11+ el.dataset['foo'];
1.5 Fratelli/Precedento/Successivo Elemento
Elementi fratelli
js// jQuery $el.siblings(); // Nativo [].filter.call(el.parentNode.children, function(child) { return child !== el; });Elementi precedenti
js// jQuery $el.prev(); // Nativo el.previousElementSibling;Elementi successivi
js// jQuery $el.next(); // Nativo el.nextElementSibling;
1.6 Il piu' vicino
Restituisce il primo elementi combiaciante il selettore fornito, attraversando dall'elemento corrente fino al document .
js// jQuery $el.closest(queryString); // Nativo - Solo ultimo, NO IE el.closest(selector); // Nativo - 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 Fino a parenti
Ottiene il parente di ogni elemento nel set corrente di elementi combiacianti, fino a ma non incluso, l'elemento combiaciante il selettorer, DOM node, o jQuery object.
js// jQuery $el.parentsUntil(selector, filter); // Nativo function parentsUntil(el, selector, filter) { const result = []; const matchesSelector = el.matches || el.webkitMatchesSelector || el.mozMatchesSelector || el.msMatchesSelector; // il match parte dal parente 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
js// jQuery $('#my-input').val(); // Native document.querySelector('#my-input').value;Get index of e.currentTarget between
.radiojs// jQuery $(e.currentTarget).index('.radio'); // Nativo [].indexOf.call(document.querySelectAll('.radio'), e.currentTarget);
1.9 Iframe Contents
$('iframe').contents()restituiscecontentDocumentper questo specifico iframeIframe contenuti
js// jQuery $iframe.contents(); // Nativo iframe.contentDocument;Iframe Query
js// jQuery $iframe.contents().find('.css'); // Nativo iframe.contentDocument.querySelectorAll('.css');
CSS & Style
2.1 CSS
Ottenere style
js// jQuery $el.css("color"); // Nativo // NOTA: Bug conosciuto, restituira' 'auto' se il valore di style e' 'auto' const win = el.ownerDocument.defaultView; // null significa che non restituira' lo psuedo style win.getComputedStyle(el, null).color;Settare style
js// jQuery $el.css({ color: "#ff0011" }); // Nativo el.style.color = '#ff0011';Ottenere/Settare Styles
Nota che se volete settare styles multipli in una sola volta, potete riferire setStyles metodo in oui-dom-utils package.
Aggiungere classe
js// jQuery $el.addClass(className); // Nativo el.classList.add(className);Rimouvere class
js// jQuery $el.removeClass(className); // Nativo el.classList.remove(className);has class
js// jQuery $el.hasClass(className); // Nativo el.classList.contains(className);Toggle class
js// jQuery $el.toggleClass(className); // Nativo el.classList.toggle(className);
2.2 Width & Height
Width e Height sono teoricamente identici, prendendo Height come esempio:
Window height
js// window height $(window).height(); // senza scrollbar, si comporta comporta jQuery window.document.documentElement.clientHeight; // con scrollbar window.innerHeight;Document height
js// jQuery $(document).height(); // Nativo document.documentElement.scrollHeight;Element height
js// jQuery $el.height(); // Nativo function getHeight(el) { const styles = this.getComputedStyles(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; } // preciso a intero(quando `border-box`, e' `height - border`; quando `content-box`, e' `height + padding`) el.clientHeight; // preciso a decimale(quando `border-box`, e' `height`; quando `content-box`, e' `height + padding + border`) el.getBoundingClientRect().height;
2.3 Position & Offset
Position
js// jQuery $el.position(); // Nativo { left: el.offsetLeft, top: el.offsetTop }Offset
js// jQuery $el.offset(); // Nativo 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
js// jQuery $(window).scrollTop(); // Nativo (document.documentElement && document.documentElement.scrollTop) || document.body.scrollTop;
Manipolazione DOM
3.1 Remove
js// jQuery $el.remove(); // Nativo el.parentNode.removeChild(el);3.2 Text
Get text
js// jQuery $el.text(); // Nativo el.textContent;Set text
js// jQuery $el.text(string); // Nativo el.textContent = string;
3.3 HTML
Ottenere HTML
js// jQuery $el.html(); // Nativo el.innerHTML;Settare HTML
js// jQuery $el.html(htmlString); // Nativo el.innerHTML = htmlString;
3.4 Append
appendere elemento figlio dopo l'ultimo elemento figlio del genitore
js// jQuery $el.append("hello"); // Nativo el.insertAdjacentHTML("beforeend","hello");3.5 Prepend
js// jQuery $el.prepend("hello"); // Nativo el.insertAdjacentHTML("afterbegin","hello");3.6 insertBefore
Inserire un nuovo node dopo l'elmento selezionato
js// jQuery $newEl.insertBefore(queryString); // Nativo const target = document.querySelector(queryString); target.parentNode.insertBefore(newEl, target);3.7 insertAfter
Insert a new node after the selected elements
js// jQuery $newEl.insertAfter(queryString); // Nativo const target = document.querySelector(queryString); target.parentNode.insertBefore(newEl, target.nextSibling);3.8 is
Restituisce
truese combacia con l'elemento selezionatojs// jQuery - Notare `is` funziona anche con `function` o `elements` non di importanza qui $el.is(selector); // Nativo el.matches(selector);
Ajax
Sostituire con fetch and fetch-jsonp
Eventi
Per una completa sostituzione con namespace e delegation, riferire a https://github.com/oneuijs/oui-dom-events
5.1 Bind un evento con on
js// jQuery $el.on(eventName, eventHandler); // Nativo el.addEventListener(eventName, eventHandler);5.2 Unbind an event with off
js// jQuery $el.off(eventName, eventHandler); // Nativo el.removeEventListener(eventName, eventHandler);5.3 Trigger
js// jQuery $(el).trigger('custom-event', {key1: 'data'}); // Nativo if (window.CustomEvent) { const event = new CustomEvent('custom-event', {detail: {key1: 'data'}}); } else { const event = document.createEvent('CustomEvent'); event.initCustomEvent('custom-event', true, true, {key1: 'data'}); } el.dispatchEvent(event);
Utilities
6.1 isArray
js// jQuery $.isArray(range); // Nativo Array.isArray(range);6.2 Trim
js// jQuery $.trim(string); // Nativo string.trim();6.3 Object Assign
Extend, usa object.assign polyfill https://github.com/ljharb/object.assign
js// jQuery $.extend({}, defaultOpts, opts); // Nativo Object.assign({}, defaultOpts, opts);6.4 Contains
js// jQuery $.contains(el, child); // Nativo el !== child && el.contains(child);
Alternative
- Forse non hai bisogno di jQuery - Esempi di come creare eventi comuni, elementi, ajax etc usando puramente javascript.
- npm-dom e webmodules - Organizzazione dove puoi trovare moduli per il DOM individuale su NPM
Supporto Browsers
| | | |
--- | --- | --- | --- | --- |
Ultimo ✔ | Ultimo ✔ | 10+ ✔ | Ultimo ✔ | 6.1+ ✔ |
Licenza
MIT
File: README-ja.md
jQueryは必要ない(You Don't Need jQuery)
フロントエンドの開発環境はめまぐるしく進化していて、最近のブラウザでは十分な質、量のDOM/BOM APIが実装されています。もうDOM操作やイベント処理のためにjQueryを覚える必要はありません。また、ReactやAngularそしてVueなどのフロントエンドライブラリの流行により、DOMを直接操作することはアンチパターンとなりました。jQueryはそれほど重要ではなくなったのです。このプロジェクトは、jQueryでの書き方の代わりとなるネイティブでの書き方(IE10以上)をまとめます。
目次
Translations
- 한국어
- 正體中文
- 简体中文
- Bahasa Melayu
- Bahasa Indonesia
- Português(PT-BR)
- Tiếng Việt Nam
- Español
- Русский
- Кыргызча
- Türkçe
- Italiano
- Français
- Polski
セレクタ
classセレクタ、idセレクタ、属性セレクタのような主要セレクタはdocument.querySelectorもしくはdocument.querySelectorAllで代替できます。
jQueryのセレクタと比べて以下の違いがあります。
document.querySelectorはセレクタにマッチする最初のエレメントを返すdocument.querySelectorAllはセレクタにマッチする全てのエレメントのNodeListを返す。Array.prototype.slice.call(document.querySelectorAll(selector) || []);で配列に変換できる。- セレクタにマッチする要素がなかった場合、jQueryは
[]を返すが、DOM APIはnullを返す。したがってNull Pointer Exceptionに注意する必要がある。もしくはdocument.querySelectorAll(selector) || []のように||を使ってデフォルト値を指定しておく。
注意:
document.querySelectorとdocument.querySelectorAllはかなり遅いです。もし、パフォーマンスが必要ならdocument.getElementByIdやdocument.getElementsByClassName、document.getElementsByTagNameを使ってください。
1.0 セレクタによる選択
js// jQuery $('selector'); // Native document.querySelectorAll('selector');1.1 クラス名による選択
js// jQuery $('.class'); // Native document.querySelectorAll('.class'); // or document.getElementsByClassName('class');1.2 idによる選択
js// jQuery $('#id'); // Native document.querySelector('#id'); // or document.getElementById('id');1.3 属性による選択
js// jQuery $('a[target=_blank]'); // Native document.querySelectorAll('a[target=_blank]');1.4 子孫要素の選択
js// jQuery $el.find('li'); // Native el.querySelectorAll('li');1.5 兄弟要素の選択
兄弟要素
js// jQuery $el.siblings(); // Native Array.prototype.filter.call(el.parentNode.children, function(child) { return child !== el; });直前の兄弟要素
js// jQuery $el.prev(); // Native el.previousElementSibling;直後の兄弟要素
js// jQuery $el.next(); // Native el.nextElementSibling;
1.6 祖先要素の選択
指定要素からdocument方向に遡って走査し、セレクタにマッチする最初の祖先要素を返します。
js// jQuery $el.closest(selector); // Native - 最近のブラウザのみ。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
指定要素からセレクタにマッチする祖先要素までdocument方向に遡って走査し、フィルタにマッチする祖先要素を全て取得します。ただし、セレクタで指定された要素は含みません。
js// jQuery $el.parentsUntil(selector, filter); // Native function parentsUntil(el, selector, filter) { const result = []; const matchesSelector = el.matches || el.webkitMatchesSelector || el.mozMatchesSelector || el.msMatchesSelector; // 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 フォーム
input/textarea
js// jQuery $('#my-input').val(); // Native document.querySelector('#my-input').value;.radio内でのe.currentTargetのインデックスを返すjs// jQuery $(e.currentTarget).index('.radio'); // Native Array.prototype.indexOf.call(document.querySelectorAll('.radio'), e.currentTarget);
1.9 iframeのコンテンツ
$('iframe').contents()はiframeのcontentDocumentを返します。Iframe contents
js// jQuery $iframe.contents(); // Native iframe.contentDocument;Iframe Query
js// jQuery $iframe.contents().find('.css'); // Native iframe.contentDocument.querySelectorAll('.css');
1.10 bodyを取得する
js// jQuery $('body'); // Native document.body;1.11 属性の設定、取得
属性値を取得する
js// jQuery $el.attr('foo'); // Native el.getAttribute('foo');属性値を設定する
js// jQuery, DOMを変化させずメモリ上で動作することに注意 $el.attr('foo', 'bar'); // Native el.setAttribute('foo', 'bar');data-属性を取得するjs// jQuery $el.data('foo'); // Native (`getAttribute`を使う) el.getAttribute('data-foo'); // Native (IE11以上のサポートなら`dataset`を使ってもよい) el.dataset['foo'];
CSSとスタイル
2.1 CSS
スタイルを取得する
js// jQuery $el.css("color"); // Native // NOTE: 既知のバグ デフォルト値が'auto'の場合、値が指定されていなくても'auto'が返る const win = el.ownerDocument.defaultView; // nullは疑似要素でないことを示している win.getComputedStyle(el, null).color;スタイルを設定する
js// jQuery $el.css({ color: "#ff0011" }); // Native el.style.color = '#ff0011';スタイルを一括取得、一括設定する
複数のスタイルを一括で設定したいなら、oui-dom-utilsのsetStyles関数を参考にすると良いでしょう。
クラスを追加する
js// jQuery $el.addClass(className); // Native el.classList.add(className);クラスを削除する
js// jQuery $el.removeClass(className); // Native el.classList.remove(className);クラスの有無をチェックする
js// jQuery $el.hasClass(className); // Native el.classList.contains(className);クラスの有無を切り替える
js// jQuery $el.toggleClass(className); // Native el.classList.toggle(className);
2.2 横幅と高さ
横幅(width)と高さ(height)の書き方はほぼ同じなので、高さ(height)の例のみを示します。
ウィンドウの高さ
js// window height $(window).height(); // jQueryのようにスクロールバーを除いた高さ window.document.documentElement.clientHeight; // スクロールバーを含めるなら window.innerHeight;ドキュメントの高さ
js// jQuery $(document).height(); // Native document.documentElement.scrollHeight;エレメントの高さ
js// 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; } // integerで取得(`border-box`の時は`height - border`が、`content-box`の時は`height + padding`が返る) el.clientHeight; // decimalで取得(`border-box`の時は`height`が、`content-box`の時は`height + padding + border`が返る) el.getBoundingClientRect().height;
2.3 PositionとOffset
Position
offset parentを起点として、エレメントの座標を取得する。
js// jQuery $el.position(); // Native { left: el.offsetLeft, top: el.offsetTop }Offset
documentを起点として、エレメントの座標を取得する。
js// 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 スクロール位置
縦スクロールバーの位置を取得する。
js// jQuery $(window).scrollTop(); // Native (document.documentElement && document.documentElement.scrollTop) || document.body.scrollTop;
DOM操作
3.1 Remove
DOMからエレメントを削除する。
js// jQuery $el.remove(); // Native el.parentNode.removeChild(el);3.2 Text
テキストを取得する
子孫エレメントも含めた全テキスト内容を取得する。
js// jQuery $el.text(); // Native el.textContent;テキストを設定する
エレメントのコンテントを指定されたテキストに設定する。
js// jQuery $el.text(string); // Native el.textContent = string;
3.3 HTML
HTMLを取得する
js// jQuery $el.html(); // Native el.innerHTML;HTMLを設定する
js// jQuery $el.html(htmlString); // Native el.innerHTML = htmlString;
3.4 Append
最後の子要素としてエレメントを追加する。
js// jQuery $el.append("hello"); // Native el.insertAdjacentHTML("beforeend","hello");3.5 Prepend
最初の子要素としてエレメントを追加する。
js// jQuery $el.prepend("hello"); // Native el.insertAdjacentHTML("afterbegin","hello");3.6 insertBefore
指定要素の後ろに新しいノードを追加する。
js// jQuery $newEl.insertBefore(queryString); // Native const target = document.querySelector(queryString); target.parentNode.insertBefore(newEl, target);3.7 insertAfter
指定要素の前に新しいノードを追加する。
js// jQuery $newEl.insertAfter(queryString); // Native const target = document.querySelector(queryString); target.parentNode.insertBefore(newEl, target.nextSibling);3.8 is
セレクタにマッチするなら
trueを返す。js// is関数は複数エレメントや関数にも対応するが、matches関数は単一エレメントのみに使える $el.is(selector); // Native el.matches(selector);3.9 clone
エレメントのディープコピーを生成する。
js// jQuery $el.clone(); // Native el.cloneNode(); // パラメータには`true`が渡され、深い複製を生成します。 // 浅い複製を生成するには、`false`を渡します。3.10 empty
全ての子ノードを削除する。
js// jQuery $el.empty(); // Native el.innerHTML = '';3.11 wrap
エレメントを指定のHTMLで囲む。
js// jQuery $('.inner').wrap(''); // Native Array.prototype.slice.call(document.querySelectorAll('.inner')).forEach(function(el){ var wrapper = document.createElement('div'); wrapper.className = 'wrapper'; el.parentNode.insertBefore(wrapper, el); el.parentNode.removeChild(el); wrapper.appendChild(el); });3.12 unwrap
セレクタにマッチしたエレメントの親要素をDOMから削除する。マッチしたエレメント自体は残す。
js// jQuery $('.inner').unwrap(); // Native Array.prototype.slice.call(document.querySelectorAll('.inner')).forEach(function(el){ Array.prototype.slice.call(el.childNodes).forEach(function(child){ el.parentNode.insertBefore(child, el); }); el.parentNode.removeChild(el); });3.13 replaceWith
セレクタにマッチしたエレメントの内容を与えられた内容に置き換える。
js// jQuery $('.inner').replaceWith(''); // Native Array.prototype.slice.call(document.querySelectorAll('.inner')).forEach(function(el){ var outer = document.createElement('div'); outer.className = 'outer'; el.parentNode.insertBefore(outer, el); el.parentNode.removeChild(el); });
Ajax
Fetch APIはXMLHttpRequestを置き換える新たな規格です。ChromeとFirefoxで動きます。レガシーなブラウザでもpolyfillを使えます。
IE9以上ならgithub/fetch、IE8以上ならfetch-ie8、jsonpを利用したいならfetch-jsonpを試してみてください。
4.1 マッチしたエレメントをサーバから取得したHTMLに置き換える。
js// jQuery $(selector).load(url, completeCallback) // Native fetch(url).then(data => data.text()).then(data => { document.querySelector(selector).innerHTML = data }).then(completeCallback)
イベント
名前空間(namespace)と委譲(delegation)を利用した完全な代替手段が必要なら、 https://github.com/oneuijs/oui-dom-events を参照してください。
5.0 ドキュメントが読み込まれたときの動作(
DOMContentLoaded)js// jQuery $(document).ready(eventHandler); // Native // DOMContentLoadedがすでに完了していないか確認する if (document.readyState !== 'loading') { eventHandler(); } else { document.addEventListener('DOMContentLoaded', eventHandler); }5.1 イベントをバインドする(
on)js// jQuery $el.on(eventName, eventHandler); // Native el.addEventListener(eventName, eventHandler);5.2 イベントをアンバインドする(
off)js// jQuery $el.off(eventName, eventHandler); // Native el.removeEventListener(eventName, eventHandler);5.3 イベントを発火させる(
trigger)js// jQuery $(el).trigger('custom-event', {key1: 'data'}); // Native if (window.CustomEvent) { const event = new CustomEvent('custom-event', {detail: {key1: 'data'}}); } else { const event = document.createEvent('CustomEvent'); event.initCustomEvent('custom-event', true, true, {key1: 'data'}); } el.dispatchEvent(event);
ユーティリティ関数
殆どのユーティリティ関数はネイティブのAPIで置き換えることができます。表記の一貫性やパフォーマンスを重視した他のライブラリを使う選択肢もあります。lodashがおすすめです。
6.1 基本的なユーティリティ関数
- isArray
配列かどうか判定する。
js// jQuery $.isArray(array); // Native Array.isArray(array);- isWindow
windowかどうか判定する。
js// jQuery $.isWindow(obj); // Native function isWindow(obj) { return obj != null && obj === obj.window; }- inArray
配列の中で、指定された値が最初に現れたインデックスを返す。(見つからなければ-1を返す)。
js// jQuery $.inArray(item, array); // Native Array.indexOf(item);- isNumeric
数値かどうか判定する。
typeofを使ってください。ライブラリを使う場合、typeofは正確でない場合があります。js// jQuery $.isNumeric(item); // Native function isNumeric(item) { return typeof item === 'number'; }- isFunction
JavaScript関数オブジェクトかどうか判定する。
js// jQuery $.isFunction(item); // Native function isFunction(item) { return typeof item === 'function'; }- isEmptyObject
空のオブジェクトである(列挙できる要素がない)か判定する。
js// jQuery $.isEmptyObject(obj); // Native function isEmptyObject(obj) { for (let key in obj) { return false; } return true; }- isPlainObject
{}もしくはnew Objectで生成されたオブジェクトであるか判定する。js// jQuery $.isPlainObject(obj); // Native function isPlainObject(obj) { if (typeof (obj) !== 'object' || obj.nodeType || obj != null && obj === obj.window) { return false; } if (obj.constructor && !{}.hasOwnProperty.call(obj.constructor.prototype, 'isPrototypeOf')) { return false; } return true; }- extend
二つ以上のオブジェクトをマージする。
object.assignはECMAScript6のAPIですが、polyfillも利用できます。js// jQuery $.extend({}, defaultOpts, opts); // Native Object.assign({}, defaultOpts, opts);- trim
前後の空白を除去する。
js// jQuery $.trim(string); // Native string.trim();- map
配列やオブジェクトを新しい配列に変換する。
js// jQuery $.map(array, function(value, index) { }); // Native array.map(function(value, index) { });- each
配列やオブジェクトに対して繰り返し処理を行う。
js// jQuery $.each(array, function(value, index) { }); // Native array.forEach(function(value, index) { });- grep
フィルター関数に合致したエレメントだけを返す。
js// jQuery $.grep(array, function(value, index) { }); // Native array.filter(function(value, index) { });- type
JavaScript「クラス」名を判定します。
js// jQuery $.type(obj); // Native Object.prototype.toString.call(obj).replace(/^\[object (.+)\]$/, '$1').toLowerCase();- merge
二つの配列をマージする。
js// jQuery $.merge(array1, array2); // Native // 重複した要素は削除されない function merge() { return Array.prototype.concat.apply([], arguments) }- now
現在の時刻を返す。
js// jQuery $.now(); // Native Date.now();- proxy
関数内で実行されるthisを任意のオブジェクトに変更する。
js// jQuery $.proxy(fn, context); // Native fn.bind(context);- makeArray
配列形式のオブジェクトを配列に変換する。
js// jQuery $.makeArray(arrayLike); // Native Array.prototype.slice.call(arrayLike); // ES6なら Array.from(arrayLike);6.2 contains
ある要素が他の要素の子孫であるか判定する。
js// jQuery $.contains(el, child); // Native el !== child && el.contains(child);6.3 globaleval
JavaScriptコードをグローバル空間で実行する。
js// jQuery $.globaleval(code); // Native function Globaleval(code) { let script = document.createElement('script'); script.text = code; document.head.appendChild(script).parentNode.removeChild(script); } // evalはcurrentコンテキストで実行される。$.globalevalのコンテキストはグローバルである。 eval(code);6.4 parse
- parseHTML
文字列をDOM nodeの配列として返します。
js// jQuery $.parseHTML(htmlString); // Native function parseHTML(string) { const tmp = document.implementation.createHTMLDocument(); tmp.body.innerHTML = string; return tmp.body.children; }- parseJSON
JSON文字列をJavaScriptに変換します。
js// jQuery $.parseJSON(str); // Native JSON.parse(str);
Promise
promiseは非同期処理の最終的な処理結果を表します。jQueryにはpromiseを扱うための独自の方法があります。ネイティブのJavaScriptではPromises/A+規格に則り、薄く、最小限のAPIを実装しています。
7.1 done, fail, always
doneはpromiseが成功(resolved)したとき、fallは失敗(rejected)したとき、alwaysはどちらの場合も呼び出されます。js// jQuery $promise.done(doneCallback).fail(failCallback).always(alwaysCallback) // Native promise.then(doneCallback, failCallback).then(alwaysCallback, alwaysCallback)7.2 when
whenは複数のpromiseを扱うときに使います。すべてのpromiseの結果が返ったときに成功となります(失敗が含まれてても成功となります)。js// jQuery $.when($promise1, $promise2).done((promise1Result, promise2Result) => {}) // Native Promise.all([$promise1, $promise2]).then([promise1Result, promise2Result] => {});7.3 Deferred
Deferredはpromiseを作成する方法の一つです。js// jQuery function asyncFunc() { var d = new $.Deferred(); setTimeout(function() { if(true) { d.resolve('some_value_compute_asynchronously'); } else { d.reject('failed'); } }, 1000); return d.promise(); } // Native function asyncFunc() { return new Promise((resolve, reject) => { setTimeout(function() { if (true) { resolve('some_value_compute_asynchronously'); } else { reject('failed'); } }, 1000); }); } // Deferred way function defer() { let resolve, reject; let promise = new Promise(function() { resolve = arguments[0]; reject = arguments[1]; }); return { resolve, reject, promise }; } function asyncFunc() { var d = defer(); setTimeout(function() { if(true) { d.resolve('some_value_compute_asynchronously'); } else { d.reject('failed'); } }, 1000); return d.promise; }
アニメーション
8.1 show、hide
js// jQuery $el.show(); $el.hide(); // Native // show関数の詳細を見たければ次のURLを参照してください // https://github.com/oneuijs/oui-dom-utils/blob/master/src/index.js#L363 el.style.display = ''|'inline'|'inline-block'|'inline-table'|'block'; el.style.display = 'none';8.2 toggle
エレメントが表示されていないなら表示し、表示されているなら非表示にします。
js// jQuery $el.toggle(); // Native if (el.ownerDocument.defaultView.getComputedStyle(el, null).display === 'none') { el.style.display = ''|'inline'|'inline-block'|'inline-table'|'block'; } else { el.style.display = 'none'; }8.3 fadeIn、fadeOut
js// jQuery $el.fadeIn(3000); $el.fadeOut(3000); // Native el.style.transition = 'opacity 3s'; // fadeIn el.style.opacity = '1'; // fadeOut el.style.opacity = '0';8.4 fadeTo
エレメントのopacityを調整してください。
js// jQuery $el.fadeTo('slow',0.15); // Native el.style.transition = 'opacity 3s'; // 'slow'は3秒だということにしている el.style.opacity = '0.15';8.5 fadeToggle
フェードイン・フェードアウトを伴ってエレメントの表示・非表示を切り替えます。
js// jQuery $el.fadeToggle(); // Native el.style.transition = 'opacity 3s'; let { opacity } = el.ownerDocument.defaultView.getComputedStyle(el, null); if (opacity === '1') { el.style.opacity = '0'; } else { el.style.opacity = '1'; }8.6 スライドアップ、スライドダウン
js// jQuery $el.slideUp(); $el.slideDown(); // Native let originHeight = '100px'; el.style.transition = 'height 3s'; // slideUp el.style.height = '0px'; // slideDown el.style.height = originHeight;8.7 slideToggle
スライドを伴って、エレメントの表示・非表示を切り替えます。
js// jQuery $el.slideToggle(); // Native let originHeight = '100px'; el.style.transition = 'height 3s'; let { height } = el.ownerDocument.defaultView.getComputedStyle(el, null); if (parseInt(height, 10) === 0) { el.style.height = originHeight; } else { el.style.height = '0px'; }8.8 animate
CSSプロパティで定義されたアニメーションを表示します。
js// jQuery $el.animate({params}, speed); // Native el.style.transition = 'all' + speed; Object.keys(params).forEach(function(key) { el.style[key] = params[key]; })
選択肢
- You Might Not Need jQuery - ネイティブのJavaScriptでイベント、エレメント、Ajaxを扱うサンプル集(英語)
- npm-dom and webmodules - npmで利用できるDOMモジュールを集めたOrganizationです
対応ブラウザ
![]() |
![]() |
![]() |
![]() |
![]() |
|---|---|---|---|---|
| Latest ✔ | Latest ✔ | 10+ ✔ | Latest ✔ | 6.1+ ✔ |
ライセンス
MIT




