Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

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

License

NotificationsYou must be signed in to change notification settings

camsong/You-Dont-Need-jQuery

Repository files navigation

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

ℹ️ Notice:

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

Table of Contents

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

Translations

Query Selector

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

  • document.querySelector returns the first matched element
  • document.querySelectorAll returns all matched elements as NodeList. It can be converted to Array usingArray.prototype.slice.call(document.querySelectorAll(selector)); or any of the methods outlined inmakeArray
  • If there are no elements matched, jQuery anddocument.querySelectorAll will return[], whereasdocument.querySelector will returnnull.

Notice:document.querySelector anddocument.querySelectorAll are quiteSLOW, thus try to usedocument.getElementById,document.getElementsByClassName ordocument.getElementsByTagName if you want to get a performance bonus.

  • 1.0 Query by selector

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

    // jQuery$('.class');// Nativedocument.querySelectorAll('.class');// ordocument.getElementsByClassName('class');
  • 1.2 Query by id

    // jQuery$('#id');// Nativedocument.querySelector('#id');// ordocument.getElementById('id');// orwindow['id']
  • 1.3 Query by attribute

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

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

    • All siblings

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

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

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

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

      // jQuery (optional selector filter)$el.nextAll($filter);// Native (optional filter function)functiongetNextSiblings(elem,filter){varsibs=[];varnextElem=elem.parentNode.firstChild;do{if(nextElem.nodeType===3)continue;// ignore text nodesif(nextElem===elem)continue;// ignore elem of targetif(nextElem===elem.nextElementSibling){if(!filter||filter(elem)){sibs.push(nextElem);elem=nextElem;}}}while(nextElem=nextElem.nextSibling)returnsibs;}

An example of filter function:

functionexampleFilter(elem){switch(elem.nodeName.toUpperCase()){case'DIV':returntrue;case'SPAN':returntrue;default:returnfalse;}}
  • 1.6 Closest

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

    // jQuery$el.closest(selector);// Native - Only latest, NO IEel.closest(selector);// Native - IE10+functionclosest(el,selector){constmatchesSelector=el.matches||el.webkitMatchesSelector||el.mozMatchesSelector||el.msMatchesSelector;while(el){if(matchesSelector.call(el,selector)){returnel;}else{el=el.parentElement;}}returnnull;}
  • 1.7 Parents Until

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

    // jQuery$el.parentsUntil(selector,filter);// NativefunctionparentsUntil(el,selector,filter){constresult=[];constmatchesSelector=el.matches||el.webkitMatchesSelector||el.mozMatchesSelector||el.msMatchesSelector;// match start from parentel=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;}returnresult;}
  • 1.8 Form

    • Input/Textarea

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

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

    $('iframe').contents() returnscontentDocument for this specific iframe

    • Iframe contents

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

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

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

    • Get an attribute

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

      // jQuery$el.attr('foo','bar');// Nativeel.setAttribute('foo','bar');
    • Get adata- attribute

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

    // jQuery$("selector:contains('text')");// Nativefunctioncontains(selector,text){varelements=document.querySelectorAll(selector);returnArray.from(elements).filter(function(element){returnRegExp(text).test(element.textContent);});}

⬆ back to top

CSS & Style

  • 2.1 CSS

    • Get style

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

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

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

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

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

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

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

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

    • Window height

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

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

      // jQuery$el.height();// NativefunctiongetHeight(el){conststyles=window.getComputedStyle(el);constheight=el.offsetHeight;constborderTopWidth=parseFloat(styles.borderTopWidth);constborderBottomWidth=parseFloat(styles.borderBottomWidth);constpaddingTop=parseFloat(styles.paddingTop);constpaddingBottom=parseFloat(styles.paddingBottom);returnheight-borderBottomWidth-borderTopWidth-paddingTop-paddingBottom;}// accurate to integer(when `border-box`, it's `height - border`; when `content-box`, it's `height + padding`)el.clientHeight;// accurate to decimal(when `border-box`, it's `height`; when `content-box`, it's `height + padding + border`)el.getBoundingClientRect().height;
  • 2.3 Position & Offset

    • Position

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

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

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

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

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

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

⬆ back to top

DOM Manipulation

  • 3.1 Remove

    Remove the element from the DOM.

    // jQuery$el.remove();// Nativeel.parentNode.removeChild(el);
  • 3.2 Text

    • Get text

      Get the combined text contents of the element including their descendants,

      // jQuery$el.text();// Nativeel.textContent;
    • Set text

      Set the content of the element to the specified text.

      // jQuery$el.text(string);// Nativeel.textContent=string;
  • 3.3 HTML

    • Get HTML

      // jQuery$el.html();// Nativeel.innerHTML;
    • Set HTML

      // jQuery$el.html(htmlString);// Nativeel.innerHTML=htmlString;
  • 3.4 Append

    Append child element after the last child of parent element

    // jQuery: unified syntax for DOMString and Node objects$parent.append(newEl|'<div>Hello World</div>');// Native: different syntaxparent.insertAdjacentHTML('beforeend','<div>Hello World</div>');parent.appendChild(newEl);// Native (ES6-way): unified syntaxparent.append(newEl|'<div>Hello World</div>');
  • 3.5 Prepend

    // jQuery: unified syntax for DOMString and Node objects$parent.prepend(newEl|'<div>Hello World</div>');// Native: different syntaxparent.insertAdjacentHTML('afterbegin','<div>Hello World</div>');parent.insertBefore(newEl,parent.firstChild);// Native (ES6-way): unified syntaxparent.prepend(newEl|'<div>Hello World</div>');
  • 3.6 insertBefore

    Insert a new node before the selected elements

    // jQuery$newEl.insertBefore(selector);// Native (HTML string)el.insertAdjacentHTML('beforebegin ','<div>Hello World</div>');// Native (Element)constel=document.querySelector(selector);if(el.parentNode){el.parentNode.insertBefore(newEl,el);}
  • 3.7 insertAfter

    Insert a new node after the selected elements

    // jQuery$newEl.insertAfter(selector);// Native (HTML string)el.insertAdjacentHTML('afterend','<div>Hello World</div>');// Native (Element)constel=document.querySelector(selector);if(el.parentNode){el.parentNode.insertBefore(newEl,el.nextSibling);}
  • 3.8 is

    Returntrue if it matches the query selector

    // 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);// Nativeel.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.

    // jQuery. Sets parameter as `true` to indicate that event handlers should be copied along with the element.$el.clone();// Nativeel.cloneNode();
  • 3.10 empty

    Remove all child nodes

    // jQuery$el.empty();// Nativeel.innerHTML=null;
  • 3.11 wrap

    Wrap an HTML structure around each element

    // jQuery$('.inner').wrap('<div></div>');// NativeArray.from(document.querySelectorAll('.inner')).forEach((el)=>{constwrapper=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

    // jQuery$('.inner').unwrap();// NativeArray.from(document.querySelectorAll('.inner')).forEach((el)=>{letelParentNode=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

    // jQuery$('.inner').replaceWith('<div></div>');// Native (alternative) - latest, Edge17+Array.from(document.querySelectorAll('.inner')).forEach((el)=>{constouter=document.createElement('div');outer.className='outer';el.replaceWith(outer);});// NativeArray.from(document.querySelectorAll('.inner')).forEach((el)=>{constouter=document.createElement('div');outer.className='outer';el.parentNode.replaceChild(outer,el);});
  • 3.14 simple parse

    Parse a string into HTML/SVG/XML

    // jQuery$(`<ol>  <li>a</li>  <li>b</li></ol><ol>  <li>c</li>  <li>d</li></ol>`);// Nativerange=document.createRange();parse=range.createContextualFragment.bind(range);parse(`<ol>  <li>a</li>  <li>b</li></ol><ol>  <li>c</li>  <li>d</li></ol>`);

⬆ back to top

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.

Trygithub/fetch on IE9+ orfetch-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.

    // jQuery$(selector).load(url,completeCallback)// Nativefetch(url).then(data=>data.text()).then(data=>{document.querySelector(selector).innerHTML=data}).then(completeCallback)

⬆ back to top

Events

For a complete replacement with namespace and delegation, refer tohttps://github.com/oneuijs/oui-dom-events

  • 5.0 Document ready byDOMContentLoaded

    // jQuery$(document).ready(eventHandler);// Native// Check if the DOMContentLoaded has already been completedif(document.readyState!=='loading'){eventHandler();}else{document.addEventListener('DOMContentLoaded',eventHandler);}// Native// Example 2 - Ternary Operator - Async// Check if the DOMContentLoaded has already been completed(asyncfunction(){(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

    // jQuery$el.on(eventName,eventHandler);// Nativeel.addEventListener(eventName,eventHandler);
  • 5.2 Unbind an event with off

    // jQuery$el.off(eventName,eventHandler);// Nativeel.removeEventListener(eventName,eventHandler);
  • 5.3 Trigger

    // jQuery$(el).trigger('custom-event',{key1:'data'});// Nativeif(window.CustomEvent){constevent=newCustomEvent('custom-event',{detail:{key1:'data'}});}else{constevent=document.createEvent('CustomEvent');event.initCustomEvent('custom-event',true,true,{key1:'data'});}el.dispatchEvent(event);

⬆ back to top

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.

    // jQuery$.isArray(array);// NativeArray.isArray(array);
    • isWindow

    Determine whether the argument is a window.

    // jQuery$.isWindow(obj);// NativefunctionisWindow(obj){returnobj!==null&&obj!==undefined&&obj===obj.window;}
    • inArray

    Search for a specified value within an array and return its index (or -1 if not found).

    // jQuery$.inArray(item,array);// Nativearray.indexOf(item)>-1;// ES6-wayarray.includes(item);
    • isNumeric

    Determine if the argument passed is numerical.Usetypeof to decide the type or thetype example for better accuracy.

    // jQuery$.isNumeric(item);// NativefunctionisNumeric(n){return!isNaN(parseFloat(n))&&isFinite(n);}
    • isFunction

    Determine if the argument passed is a JavaScript function object.

    // jQuery$.isFunction(item);// NativefunctionisFunction(item){if(typeofitem==='function'){returntrue;}vartype=Object.prototype.toString.call(item);returntype==='[object Function]'||type==='[object GeneratorFunction]';}
    • isEmptyObject

    Check to see if an object is empty (contains no enumerable properties).

    // jQuery$.isEmptyObject(obj);// NativefunctionisEmptyObject(obj){returnObject.keys(obj).length===0;}
    • isPlainObject

    Check to see if an object is a plain object (created using “{}” or “new Object”).

    // jQuery$.isPlainObject(obj);// NativefunctionisPlainObject(obj){if(typeof(obj)!=='object'||obj.nodeType||obj!==null&&obj!==undefined&&obj===obj.window){returnfalse;}if(obj.constructor&&!Object.prototype.hasOwnProperty.call(obj.constructor.prototype,'isPrototypeOf')){returnfalse;}returntrue;}
    • 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 apolyfill.

    // jQuery$.extend({},object1,object2);// NativeObject.assign({},object1,object2);
    • trim

    Remove the white-space from the beginning and end of a string.

    // jQuery$.trim(string);// Nativestring.trim();
    • map

    Translate all items in an array or object to new array of items.

    // jQuery$.map(array,(value,index)=>{});// Nativearray.map((value,index)=>{});
    • each

    A generic iterator function, which can be used to seamlessly iterate over both objects and arrays.

    // jQuery$.each(array,(index,value)=>{});// Nativearray.forEach((value,index)=>{});
    • grep

    Finds the elements of an array which satisfy a filter function.

    // jQuery$.grep(array,(value,index)=>{});// Nativearray.filter((value,index)=>{});
    • type

    Determine the internal JavaScript [Class] of an object.

    // jQuery$.type(obj);// Nativefunctiontype(item){constreTypeOf=/(?:^\[object\s(.*?)\]$)/;returnObject.prototype.toString.call(item).replace(reTypeOf,'$1').toLowerCase();}
    • merge

    Merge the contents of two arrays together into the first array.

    // jQuery, doesn't remove duplicate items$.merge(array1,array2);// Native, doesn't remove duplicate itemsfunctionmerge(...args){return[].concat(...args)}// ES6-way, doesn't remove duplicate itemsarray1=[...array1, ...array2]// Set version, does remove duplicate itemsfunctionmerge(...args){returnArray.from(newSet([].concat(...args)))}
    • now

    Return a number representing the current time.

    // jQuery$.now();// NativeDate.now();
    • proxy

    Takes a function and returns a new one that will always have a particular context.

    // jQuery$.proxy(fn,context);// Nativefn.bind(context);

    + makeArray

    Convert an array-like object into a true JavaScript array.

    // jQuery$.makeArray(arrayLike);// NativeArray.prototype.slice.call(arrayLike);// ES6-way: Array.from() methodArray.from(arrayLike);// ES6-way: spread operator[...arrayLike];
  • 6.2 Contains

    Check to see if a DOM element is a descendant of another DOM element.

    // jQuery$.contains(el,child);// Nativeel!==child&&el.contains(child);
  • 6.3 Globaleval

    Execute some JavaScript code globally.

    // jQuery$.globaleval(code);// NativefunctionGlobaleval(code){constscript=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.

    // jQuery$.parseHTML(htmlString);// NativefunctionparseHTML(string){constcontext=document.implementation.createHTMLDocument();// Set the base href for the created document so any parsed elements with URLs// are based on the document's URLconstbase=context.createElement('base');base.href=document.location.href;context.head.appendChild(base);context.body.innerHTML=string;returncontext.body.children;}
  • 6.5 exists

  • exists

    Check if an element exists in the DOM

    // jQueryif($('selector').length){// exists}// Nativevarelement=document.getElementById('elementId');if(typeof(element)!='undefined'&&element!=null){// exists}

⬆ back to top

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 thePromises/A+ specification.

  • 7.1 done, fail, always

    done is called when promise is resolved,fail is called when promise is rejected,always is called when promise is either resolved or rejected.

    // jQuery$promise.done(doneCallback).fail(failCallback).always(alwaysCallback)// Nativepromise.then(doneCallback,failCallback).then(alwaysCallback,alwaysCallback)
  • 7.2 when

    when is used to handle multiple promises. It will resolve when all promises are resolved, and reject if either one is rejected.

    // jQuery$.when($promise1,$promise2).done((promise1Result,promise2Result)=>{});// NativePromise.all([$promise1,$promise2]).then([promise1Result,promise2Result]=>{});
  • 7.3 Deferred

    Deferred is a way to create promises.

    // jQueryfunctionasyncFunc(){constdefer=new$.Deferred();setTimeout(()=>{if(true){defer.resolve('some_value_computed_asynchronously');}else{defer.reject('failed');}},1000);returndefer.promise();}// NativefunctionasyncFunc(){returnnewPromise((resolve,reject)=>{setTimeout(()=>{if(true){resolve('some_value_computed_asynchronously');}else{reject('failed');}},1000);});}// Deferred wayfunctiondefer(){constdeferred={};constpromise=newPromise((resolve,reject)=>{deferred.resolve=resolve;deferred.reject=reject;});deferred.promise=()=>{returnpromise;};returndeferred;}functionasyncFunc(){constdefer=defer();setTimeout(()=>{if(true){defer.resolve('some_value_computed_asynchronously');}else{defer.reject('failed');}},1000);returndefer.promise();}

⬆ back to top

Animation

  • 8.1 Show & Hide

    // 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#L363el.style.display=''|'inline'|'inline-block'|'inline-table'|'block';el.style.display='none';
  • 8.2 Toggle

    Display or hide the element.

    // jQuery$el.toggle();// Nativeif(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

    // jQuery$el.fadeIn(3000);$el.fadeOut(3000);// Native fadeOutfunctionfadeOut(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 fadeInfunctionfadeIn(elem,ms){elem.style.opacity=0;if(ms){letopacity=0;consttimer=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.

    // jQuery$el.fadeTo('slow',0.15);// Nativeel.style.transition='opacity 3s';// assume 'slow' equals 3 secondsel.style.opacity='0.15';
  • 8.5 FadeToggle

    Display or hide the element by animating their opacity.

    // jQuery$el.fadeToggle();// Nativeel.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

    // jQuery$el.slideUp();$el.slideDown();// NativeconstoriginHeight='100px';el.style.transition='height 3s';// slideUpel.style.height='0px';// slideDownel.style.height=originHeight;
  • 8.7 SlideToggle

    Display or hide the element with a sliding motion.

    // jQuery$el.slideToggle();// NativeconstoriginHeight='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.

    // jQuery$el.animate({ params},speed);// Nativeel.style.transition='all '+speed;Object.keys(params).forEach((key)=>{el.style[key]=params[key];});

Alternatives

Browser Support

ChromeFirefoxIEOperaSafari
Latest ✔Latest ✔10+ ✔Latest ✔6.1+ ✔

License

MIT

About

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

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Contributors91


[8]ページ先頭

©2009-2025 Movatter.jp