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

Automatically finds jQuery methods from existing projects and generates vanilla js alternatives.

License

NotificationsYou must be signed in to change notification settings

sachinchoolur/jquery-to-javascript-converter

Repository files navigation

npmlicense

Test coverage

StatementsFunctionsLines
StatementsFunctionsLines

jQuery to JavaScript converter

Automatically find jQuery methods from existing projects and generate vanilla js alternatives.

Why

I've been working on removing jQuery dependency from multiple projects includinglightGallery lately. Most of the projects use only 15% to 20% or less than 30% of the jquery methodsAnd in most of the cases, I didn't want to support all the edge cases or legacy browsers. The hardest part was finding the jQuery methods in the existing project and writing the alternative vanilla js methods without making much changes in the codebase. So I wrote this library which automatically finds jquery methods in any particular JavaScript file and generates readable, chainable vanilla js alternatives. This can also be useful if you want to generate your own utility methods similar to jQuery.

Installation and Usage

You can install jquery-to-js using npm:

npm install -g jquery-to-js
  • Find all jQuery methods fromsample.js and write vanillaJs alternatives in out.js
jquery-to-js src/sample.js out.js
  • Find all jQuery methods from all matching files and write vanillaJs alternatives in out.js
jquery-to-js"src/*.js" out.js
  • Build vanillaJs alternatives for the all available jQuery methods
jquery-to-js --build-all out.js
  • Build vanillaJs alternatives for the specified jQuery methods
jquery-to-js --methods"addClass, removeClass, attr" -o utils.js

Please note that, the utility functions generated byjquery-to-js are not completely equivalent to jQuery methods in all scenarios. Please consider this as a starting point and validate before you adopt it.

Basic Concepts

The generated vanilla JS methods are chainable and can be applied to all matching elements like jQuery.

Note: The below code is just to demonstrate the basics concepts and not covered all scenarios.

exportclassUtils{constructor(selector){this.elements=Utils.getSelector(selector);this.element=this.get(0);returnthis;}staticgetSelector(selector,context=document){if(typeofselector!=='string'){returnselector;}if(isId(selector)){returndocument.getElementById(selector.substring(1))}returncontext.querySelectorAll(selector);}each(func){if(!this.elements){returnthis;}if(this.elements.length!==undefined){[].forEach.call(this.elements,func);}else{func(this.element,0);}returnthis;}siblings(){if(!this.element){returnthis;}constelements=[].filter.call(this.element.parentNode.children,(child)=>child!==this.element);returnnewUtils(elements);}get(index){if(index!==undefined){returnthis.elements[index];}returnthis.elements;}addClass(classNames=''){this.each((el)=>{// IE doesn't support multiple argumentsclassNames.split(' ').forEach((className)=>{el.classList.add(className);});});returnthis;}}exportdefaultfunction$utils(selector){returnnewUtils(selector);}

Usage

<ul><liclass="jquery">jQuery</li><liclass="react">React</li><liclass="vue">Vue.js</li><liclass="angular">Angular</li><liclass="lit">Lit</li></ul>
.highlight {background-color: red;color:#fff;}
$utils(".vue").siblings().addClass("highlight");

Demo -https://codepen.io/sachinchoolur/pen/oNWNdxE

You can see that theaddClass method is depended on theeach method, so if you generate addClass method usingjquery-to-js --methods "addClass" -o utils.js the output file will containaddClass andeach methods.

Similarly, all the examples you see below, will add it's dependencies when you generate it usingjquery-to-js

List of jQuery alternative methods in alphabetical order

addClass

Adds the specified class(es) to each element in the set of matched elements.

addClass(classNames=''){this.each((el)=>{classNames.split(' ').forEach((className)=>{el.classList.add(className);});});returnthis;}
// Usage$utils('ul li').addClass('myClass yourClass');
append

Insert content, specified by the parameter, to the end of each element in the set of matched elements.

append(html){this.each((el)=>{if(typeofhtml==='string'){el.insertAdjacentHTML('beforeend',html);}else{el.appendChild(html);}});returnthis;}
attr

Get the value of an attribute for the first element in the set of matched elements or set one or more attributes for every matched element.

attr(name,value){if(value===undefined){if(!this.element){return'';}returnthis.element.getAttribute(name);}this.each((el)=>{el.setAttribute(name,value);});returnthis;}
children

Get the children of each element in the set of matched elements, optionally filtered by a selector.

children(){returnnewUtils(this.element.children);}
closest

For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.

closest(selector){if(!this.element){returnthis;}constmatchesSelector=this.element.matches||this.element.webkitMatchesSelector||this.element.mozMatchesSelector||this.element.msMatchesSelector;while(this.element){if(matchesSelector.call(this.element,selector)){returnnewUtils(this.element);}this.element=this.element.parentElement;}returnthis;}
css

Get the computed style properties for the first element in the set of matched elements.

css(css,value){if(value!==undefined){this.each((el)=>{Utils.setCss(el,css,value);});returnthis;}if(typeofcss==='object'){for(constpropertyincss){if(Object.prototype.hasOwnProperty.call(css,property)){this.each((el)=>{Utils.setCss(el,property,css[property]);});}}returnthis;}constcssProp=Utils.camelCase(css);constproperty=Utils.styleSupport(cssProp);returngetComputedStyle(this.element)[property];}
data

Store arbitrary data associated with the matched elements.

data(name,value){returnthis.attr(`data-${name}`,value);}
each

Iterate over a jQuery object, executing a function for each matched element.

each(func){if(!this.elements){returnthis;}if(this.elements.length!==undefined){[].slice.call(this.elements).forEach((el,index)=>{func.call(el,el,index);});}else{func.call(this.element,this.element,0);}returnthis;}
empty

Remove all child nodes of the set of matched elements from the DOM.

empty(){this.each((el)=>{el.innerHTML='';});returnthis;}
eq

Reduce the set of matched elements to the one at the specified index.

eq(index){returnnewUtils(this.elements[index]);}
find

Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element.

find(selector){returnnewUtils(Utils.getSelector(selector,this.element));}
first

Reduce the set of matched elements to the first in the set.

first(){if(this.elements&&this.elements.length!==undefined){returnnewUtils(this.elements[0]);}returnnewUtils(this.elements);}
get

Load data from the server using a HTTP GET request.

get(){returnthis.elements;}
hasClass

Determine whether any of the matched elements are assigned the given class.

hasClass(className){if(!this.element){returnfalse;}returnthis.element.classList.contains(className);}
height

Get the current computed height for the first element in the set of matched elements.

height(){if(!this.element){return0;}conststyle=window.getComputedStyle(this.element,null);returnparseFloat(style.height.replace('px',''));}
html

Get the HTML contents of the first element in the set of matched elements.

html(html){if(html===undefined){if(!this.element){return'';}returnthis.element.innerHTML;}this.each((el)=>{el.innerHTML=html;});returnthis;}
index

Search for a given element from among the matched elements.

index(){if(!this.element)return-1;leti=0;do{i++;}while((this.element=this.element.previousElementSibling));returni;}
is

Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments.

is(el){if(typeofel==='string'){return(this.element.matches||this.element.matchesSelector||this.element.msMatchesSelector||this.element.mozMatchesSelector||this.element.webkitMatchesSelector||this.element.oMatchesSelector).call(this.element,el);}returnthis.element===(el.element||el);}
next

Get the immediately following sibling of each element in the set of matched elements. If a selector is provided, it retrieves the next sibling only if it matches that selector.

next(){if(!this.element){returnthis;}returnnewUtils(this.element.nextElementSibling);}
nextAll

Get all following siblings of each element in the set of matched elements, optionally filtered by a selector.

nextAll(filter){if(!this.element){returnthis;}constsibs=[];letnextElem=this.element.parentNode.firstChild;do{if(nextElem.nodeType===3)continue;// ignore text nodesif(nextElem===this.element)continue;// ignore this.element of targetif(nextElem===this.element.nextElementSibling){if(!filter||filter(this.element)){sibs.push(nextElem);this.element=nextElem;}}}while((nextElem=nextElem.nextSibling));returnnewUtils(sibs);}
off

Remove an event handler.

off(event){if(!this.elements){returnthis;}Object.keys(Utils.eventListeners).forEach((eventName)=>{if(Utils.isEventMatched(event,eventName)){Utils.eventListeners[eventName].forEach((listener)=>{this.each((el)=>{el.removeEventListener(eventName.split('.')[0],listener);});});}});returnthis;}
offset

Get the current coordinates of the first element in the set of matched elements, relative to the document.

offset(){if(!this.element){return{left:0,top:0,};}constbox=this.element.getBoundingClientRect();return{top:box.top+window.pageYOffset-document.documentElement.clientTop,left:box.left+window.pageXOffset-document.documentElement.clientLeft,};}
offsetParent

Get the closest ancestor element that is positioned.

offsetParent(){if(!this.element){returnthis;}returnnewUtils(this.element.offsetParent);}
on

Attach an event handler function for one or more events to the selected elements.

on(events,listener){if(!this.elements){returnthis;}events.split(' ').forEach((event)=>{if(!Array.isArray(Utils.eventListeners[event])){Utils.eventListeners[event]=[];}Utils.eventListeners[event].push(listener);this.each((el)=>{el.addEventListener(event.split('.')[0],listener);});});returnthis;}
one

Attach a handler to an event for the elements. The handler is executed at most once per element per event type.

one(event,listener){this.each((el)=>{newUtils(el).on(event,()=>{newUtils(el).off(event);listener(event);});});returnthis;}
outerHeight

Get the current computed outer height (including padding, border, and optionally margin) for the first element in the set of matched elements.

outerHeight(margin){if(!this.element){return0;}if(margin!==undefined){letheight=this.element.offsetHeight;conststyle=getComputedStyle(this.element);height+=parseInt(style.marginTop,10)+parseInt(style.marginBottom,10);returnheight;}returnthis.element.offsetHeight;}
outerWidth

Get the current computed outer width (including padding, border, and optionally margin) for the first element in the set of matched elements.

outerWidth(margin){if(!this.element){return0;}if(margin!==undefined){letwidth=this.element.offsetWidth;conststyle=window.getComputedStyle(this.element);width+=parseInt(style.marginLeft,10)+parseInt(style.marginRight,10);returnwidth;}returnthis.element.offsetWidth;}
parent

Get the parent of each element in the current set of matched elements, optionally filtered by a selector.

parent(){returnnewUtils(this.element.parentElement);}
parentsUntil

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.

parentsUntil(selector,filter){if(!this.element){returnthis;}constresult=[];constmatchesSelector=this.element.matches||this.element.webkitMatchesSelector||this.element.mozMatchesSelector||this.element.msMatchesSelector;// match start from parentletel=this.element.parentElement;while(el&&!matchesSelector.call(el,selector)){if(!filter){result.push(el);}elseif(matchesSelector.call(el,filter)){result.push(el);}el=el.parentElement;}returnnewUtils(result);}
position

Get the current coordinates of the first element in the set of matched elements, relative to the offset parent.

position(){return{left:this.element.offsetLeft,top:this.element.offsetTop,};}
prepend

Insert content, specified by the parameter, to the beginning of each element in the set of matched elements.

prepend(html){this.each((el)=>{if(typeofhtml==='string'){el.insertAdjacentHTML('afterbegin',html);}else{el.insertBefore(html,el.firstChild);}});returnthis;}
prev

Get the immediately preceding sibling of each element in the set of matched elements. If a selector is provided, it retrieves the previous sibling only if it matches that selector.

prev(){if(!this.element){returnthis;}returnnewUtils(this.element.previousElementSibling);}
prevAll

Get all preceding siblings of each element in the set of matched elements, optionally filtered by a selector, in the reverse document order.

prevAll(filter){if(!this.element){returnthis;}constsibs=[];while((this.element=this.element.previousSibling)){if(this.element.nodeType===3){continue;// ignore text nodes}if(!filter||filter(this.element))sibs.push(this.element);}returnnewUtils(sibs);}
remove

Remove the set of matched elements from the DOM.

remove(){this.each((el)=>{el.parentNode.removeChild(el);});returnthis;}
removeAttr

Remove an attribute from each element in the set of matched elements.

removeAttr(attributes){constattrs=attributes.split(' ');this.each((el)=>{attrs.forEach((attr)=>el.removeAttribute(attr));});returnthis;}
removeClass

Remove a single class or multiple classes from each element in the set of matched elements.

removeClass(classNames){this.each((el)=>{// IE doesn't support multiple argumentsclassNames.split(' ').forEach((className)=>{el.classList.remove(className);});});returnthis;}
siblings

Get the siblings of each element in the set of matched elements, optionally filtered by a selector.

siblings(){if(!this.element){returnthis;}constelements=Array.prototype.filter.call(this.element.parentNode.children,(child)=>child!==this.element);returnnewUtils(elements);}
text

Get the combined text contents of each element in the set of matched elements, including their descendants.

text(text){if(text===undefined){if(!this.element){return'';}returnthis.element.textContent;}this.each((el)=>{el.textContent=text;});returnthis;}
toggleClass

Add or remove one or more classes from each element in the set of matched elements, depending on either the class’s presence or the value of the state argument.

toggleClass(className){if(!this.element){returnthis;}this.element.classList.toggle(className);}
trigger

Execute all handlers and behaviors attached to the matched elements for the given event type.

trigger(event,detail){if(!this.element){returnthis;}consteventName=event.split('.')[0];constisNativeEvent=typeofdocument.body[`on${eventName}`]!=='undefined';if(isNativeEvent){this.each((el)=>{el.dispatchEvent(newEvent(eventName));});returnthis;}constcustomEvent=newCustomEvent(eventName,{detail:detail||null,});this.each((el)=>{el.dispatchEvent(customEvent);});returnthis;}
unwrap

Remove the parents of the set of matched elements from the DOM, leaving the matched elements in their place.

unwrap(){this.each((el)=>{constelParentNode=el.parentNode;if(elParentNode!==document.body){elParentNode.parentNode.insertBefore(el,elParentNode);elParentNode.parentNode.removeChild(elParentNode);}});returnthis;}
val

Get the current value of the first element in the set of matched elements.

val(value){if(!this.element){return'';}if(value===undefined){returnthis.element.value;}this.element.value=value;}
width

Get the current computed width for the first element in the set of matched elements.

width(){if(!this.element){return0;}conststyle=window.getComputedStyle(this.element,null);returnparseFloat(style.width.replace('px',''));}
wrap

Wrap an HTML structure around each element in the set of matched elements.

wrap(className){this.each((el)=>{constwrapper=document.createElement('div');wrapper.className=className;el.parentNode.insertBefore(wrapper,el);wrapper.appendChild(el);});returnthis;}

Browser support - IE 11+

About

Automatically finds jQuery methods from existing projects and generates vanilla js alternatives.

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Contributors4

  •  
  •  
  •  
  •  

[8]ページ先頭

©2009-2025 Movatter.jp