![npm](https://img.shields.io/npm/v/jquery-to-js.svg?color=red)
![license](https://badgen.net/github/license/sachinchoolur/jquery-to-javascript-converter)

#### Test coverage

| Statements                                                                      | Functions                                                                   | Lines                                                               |
| ------------------------------------------------------------------------------- | --------------------------------------------------------------------------- | ------------------------------------------------------------------- |
| ![Statements](https://img.shields.io/badge/statements-99.64%25-brightgreen.svg) | ![Functions](https://img.shields.io/badge/functions-100%25-brightgreen.svg) | ![Lines](https://img.shields.io/badge/lines-100%25-brightgreen.svg) |

# 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 including [lightGallery](https://github.com/sachinchoolur/lightGallery) lately. Most of the projects use only 15% to 20% or less than 30% of the jquery methods
And 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:

```sh
npm install -g jquery-to-js
```

-   Find all jQuery methods from `sample.js` and write vanillaJs alternatives in out.js

```sh
jquery-to-js src/sample.js out.js
```

-   Find all jQuery methods from all matching files and write vanillaJs alternatives in out.js

```sh
jquery-to-js "src/*.js" out.js
```

-   Build vanillaJs alternatives for the all available jQuery methods

```sh
jquery-to-js --build-all out.js
```

-   Build vanillaJs alternatives for the specified jQuery methods

```sh
jquery-to-js --methods "addClass, removeClass, attr" -o utils.js
```

Please note that, the utility functions generated by `jquery-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. 

```js
export class Utils {
  constructor(selector) {
    this.elements = Utils.getSelector(selector);
    this.element = this.get(0);
    return this;
  }

  static getSelector(selector, context = document) {
    if (typeof selector !== 'string') {
      return selector;
    }
    if (isId(selector)) {
      return document.getElementById(selector.substring(1))
    }
    return context.querySelectorAll(selector);
  }

  each(func) {
    if (!this.elements) {
      return this;
    }
    if (this.elements.length !== undefined) {
      [].forEach.call(this.elements, func);
    } else {
      func(this.element, 0);
    }
    return this;
  }

  siblings() {
    if (!this.element) {
      return this;
    }
    const elements = [].filter.call(
      this.element.parentNode.children,
      (child) => child !== this.element
    );
    return new Utils(elements);
  }

  get(index) {
    if (index !== undefined) {
      return this.elements[index];
    }
    return this.elements;
  }

  addClass(classNames = '') {
    this.each((el) => {
      // IE doesn't support multiple arguments
      classNames.split(' ').forEach((className) => {
        el.classList.add(className);
      });
    });
    return this;
  }
}

export default function $utils(selector) {
  return new Utils(selector);
}
```

#### Usage

```html
<ul>
  <li class="jquery">jQuery</li>
  <li class="react">React</li>
  <li class="vue">Vue.js</li>
  <li class="angular">Angular</li>
  <li class="lit">Lit</li>
</ul>
```

```css
.highlight {
  background-color: red;
  color: #fff;
}
```

```js
$utils(".vue").siblings().addClass("highlight");
```

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

You can see that the `addClass` method is depended on the `each` method, so if you generate addClass method using `jquery-to-js --methods "addClass" -o utils.js` the output file will contain `addClass` and `each` methods.

Similarly, all the examples you see below, will add it's dependencies when you generate it using `jquery-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.



```js
addClass(classNames = '') {
  this.each((el) => {
    classNames.split(' ').forEach((className) => {
      el.classList.add(className);
    });
  });
  return this;
}
```

```js
// 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.
```js
append(html) {
  this.each((el) => {
    if (typeof html === 'string') {
      el.insertAdjacentHTML('beforeend', html);
    } else {
      el.appendChild(html);
    }
  });
  return this;
}
```

##### 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.

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

##### children
Get the children of each element in the set of matched elements, optionally filtered by a selector.
```js
children() {
  return new Utils(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.
```js
closest(selector) {
  if (!this.element) {
    return this;
  }
  const matchesSelector =
    this.element.matches ||
    this.element.webkitMatchesSelector ||
    this.element.mozMatchesSelector ||
    this.element.msMatchesSelector;

  while (this.element) {
    if (matchesSelector.call(this.element, selector)) {
      return new Utils(this.element);
    }
    this.element = this.element.parentElement;
  }
  return this;
}
```

##### css
Get the computed style properties for the first element in the set of matched elements.
```js
css(css, value) {
  if (value !== undefined) {
    this.each((el) => {
      Utils.setCss(el, css, value);
    });
    return this;
  }
  if (typeof css === 'object') {
    for (const property in css) {
      if (Object.prototype.hasOwnProperty.call(css, property)) {
        this.each((el) => {
          Utils.setCss(el, property, css[property]);
        });
      }
    }
    return this;
  }
  const cssProp = Utils.camelCase(css);
  const property = Utils.styleSupport(cssProp);
  return getComputedStyle(this.element)[property];
}
```

##### data

Store arbitrary data associated with the matched elements.

```js
data(name, value) {
  return this.attr(`data-${name}`, value);
}
```

##### each

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

```js
each(func) {
    if (!this.elements) {
        return this;
    }
    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);
    }
    return this;
}
```

##### empty
Remove all child nodes of the set of matched elements from the DOM.
```js
empty() {
  this.each((el) => {
    el.innerHTML = '';
  });
  return this;
}
```

##### eq
Reduce the set of matched elements to the one at the specified index.
```js
eq(index) {
  return new Utils(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.
```js
find(selector) {
  return new Utils(Utils.getSelector(selector, this.element));
}
```

##### first
Reduce the set of matched elements to the first in the set.
```js
first() {
  if (this.elements && this.elements.length !== undefined) {
    return new Utils(this.elements[0]);
  }
  return new Utils(this.elements);
}
```

##### get
Load data from the server using a HTTP GET request.
```js
get() {
  return this.elements;
}
```

##### hasClass
Determine whether any of the matched elements are assigned the given class.
```js
hasClass(className) {
  if (!this.element) {
    return false;
  }
  return this.element.classList.contains(className);
}
```

##### height
Get the current computed height for the first element in the set of matched elements.
```js
height() {
  if (!this.element) {
    return 0;
  }
  const style = window.getComputedStyle(this.element, null);
  return parseFloat(style.height.replace('px', ''));
}
```

##### html
Get the HTML contents of the first element in the set of matched elements.
```js
html(html) {
  if (html === undefined) {
    if (!this.element) {
      return '';
    }
    return this.element.innerHTML;
  }
  this.each((el) => {
    el.innerHTML = html;
  });
  return this;
}
```

##### index

Search for a given element from among the matched elements.
```js
index() {
  if (!this.element) return -1;
  let i = 0;
  do {
    i++;
  } while ((this.element = this.element.previousElementSibling));
  return i;
}
```

##### 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.
```js
is(el) {
  if (typeof el === 'string') {
    return (
      this.element.matches ||
      this.element.matchesSelector ||
      this.element.msMatchesSelector ||
      this.element.mozMatchesSelector ||
      this.element.webkitMatchesSelector ||
      this.element.oMatchesSelector
    ).call(this.element, el);
  }
  return this.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.

```js
next() {
  if (!this.element) {
    return this;
  }
  return new Utils(this.element.nextElementSibling);
}
```

##### nextAll
Get all following siblings of each element in the set of matched elements, optionally filtered by a selector.
```js
nextAll(filter) {
  if (!this.element) {
    return this;
  }
  const sibs = [];
  let nextElem = this.element.parentNode.firstChild;
  do {
    if (nextElem.nodeType === 3) continue; // ignore text nodes
    if (nextElem === this.element) continue; // ignore this.element of target
    if (nextElem === this.element.nextElementSibling) {
      if (!filter || filter(this.element)) {
        sibs.push(nextElem);
        this.element = nextElem;
      }
    }
  } while ((nextElem = nextElem.nextSibling));
  return new Utils(sibs);
}
```

##### off
Remove an event handler.
```js
off(event) {
  if (!this.elements) {
    return this;
  }
  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
          );
        });
      });
    }
  });

  return this;
}
```

##### offset
Get the current coordinates of the first element in the set of matched elements, relative to the document.
```js
offset() {
  if (!this.element) {
    return {
      left: 0,
      top: 0,
    };
  }
  const box = 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.
```js
offsetParent() {
  if (!this.element) {
    return this;
  }
  return new Utils(this.element.offsetParent);
}
```

##### on
Attach an event handler function for one or more events to the selected elements.
```js
on(events, listener) {
  if (!this.elements) {
    return this;
  }
  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);
    });
  });

  return this;
}
```

##### one
Attach a handler to an event for the elements. The handler is executed at most once per element per event type.
```js
one(event, listener) {
  this.each((el) => {
    new Utils(el).on(event, () => {
      new Utils(el).off(event);
      listener(event);
    });
  });
  return this;
}
```

##### outerHeight
Get the current computed outer height (including padding, border, and optionally margin) for the first element in the set of matched elements.
```js
outerHeight(margin) {
  if (!this.element) {
    return 0;
  }
  if (margin !== undefined) {
    let height = this.element.offsetHeight;
    const style = getComputedStyle(this.element);

    height +=
      parseInt(style.marginTop, 10) +
      parseInt(style.marginBottom, 10);
    return height;
  }
  return this.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.
```js
outerWidth(margin) {
  if (!this.element) {
    return 0;
  }
  if (margin !== undefined) {
    let width = this.element.offsetWidth;
    const style = window.getComputedStyle(this.element);

    width +=
      parseInt(style.marginLeft, 10) +
      parseInt(style.marginRight, 10);
    return width;
  }
  return this.element.offsetWidth;
}
```

##### parent

Get the parent of each element in the current set of matched elements, optionally filtered by a selector.
```js
parent() {
  return new Utils(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. 
```js
parentsUntil(selector, filter) {
  if (!this.element) {
    return this;
  }
  const result = [];
  const matchesSelector =
    this.element.matches ||
    this.element.webkitMatchesSelector ||
    this.element.mozMatchesSelector ||
    this.element.msMatchesSelector;

  // match start from parent
  let el = this.element.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 new Utils(result);
}
```

##### position
Get the current coordinates of the first element in the set of matched elements, relative to the offset parent.
```js
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.
```js
prepend(html) {
  this.each((el) => {
    if (typeof html === 'string') {
      el.insertAdjacentHTML('afterbegin', html);
    } else {
      el.insertBefore(html, el.firstChild);
    }
  });
  return this;
}
```

##### 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.
```js
prev() {
  if (!this.element) {
    return this;
  }
  return new Utils(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.
```js
prevAll(filter) {
  if (!this.element) {
    return this;
  }
  const sibs = [];
  while ((this.element = this.element.previousSibling)) {
    if (this.element.nodeType === 3) {
      continue; // ignore text nodes
    }
    if (!filter || filter(this.element)) sibs.push(this.element);
  }
  return new Utils(sibs);
}
```

##### remove
Remove the set of matched elements from the DOM.
```js
remove() {
  this.each((el) => {
    el.parentNode.removeChild(el);
  });
  return this;
}
```

##### removeAttr

Remove an attribute from each element in the set of matched elements.
```js
removeAttr(attributes) {
  const attrs = attributes.split(' ');
  this.each((el) => {
    attrs.forEach((attr) => el.removeAttribute(attr));
  });
  return this;
}
```

##### removeClass
Remove a single class or multiple classes from each element in the set of matched elements.
```js
removeClass(classNames) {
  this.each((el) => {
    // IE doesn't support multiple arguments
    classNames.split(' ').forEach((className) => {
      el.classList.remove(className);
    });
  });
  return this;
}
```

##### siblings
Get the siblings of each element in the set of matched elements, optionally filtered by a selector.
```js
siblings() {
  if (!this.element) {
    return this;
  }
  const elements = Array.prototype.filter.call(
    this.element.parentNode.children,
    (child) => child !== this.element
  );
  return new Utils(elements);
}
```

##### text
Get the combined text contents of each element in the set of matched elements, including their descendants.
```js
text(text) {
  if (text === undefined) {
    if (!this.element) {
      return '';
    }
    return this.element.textContent;
  }
  this.each((el) => {
    el.textContent = text;
  });
  return this;
}
```

##### 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.
```js
toggleClass(className) {
  if (!this.element) {
    return this;
  }
  this.element.classList.toggle(className);
}
```

##### trigger
Execute all handlers and behaviors attached to the matched elements for the given event type.
```js
trigger(event, detail) {
  if (!this.element) {
    return this;
  }
  const eventName = event.split('.')[0];
  const isNativeEvent =
    typeof document.body[`on${eventName}`] !== 'undefined';
  if (isNativeEvent) {
    this.each((el) => {
      el.dispatchEvent(new Event(eventName));
    });
    return this;
  }
  const customEvent = new CustomEvent(eventName, {
    detail: detail || null,
  });
  this.each((el) => {
    el.dispatchEvent(customEvent);
  });
  return this;
}
```

##### unwrap
Remove the parents of the set of matched elements from the DOM, leaving the matched elements in their place.
```js
unwrap() {
  this.each((el) => {
    const elParentNode = el.parentNode;

    if (elParentNode !== document.body) {
      elParentNode.parentNode.insertBefore(el, elParentNode);
      elParentNode.parentNode.removeChild(elParentNode);
    }
  });
  return this;
}
```

##### val
Get the current value of the first element in the set of matched elements.
```js
val(value) {
  if (!this.element) {
    return '';
  }
  if (value === undefined) {
    return this.element.value;
  }
  this.element.value = value;
}
```

##### width
Get the current computed width for the first element in the set of matched elements.
```js
width() {
  if (!this.element) {
    return 0;
  }
  const style = window.getComputedStyle(this.element, null);
  return parseFloat(style.width.replace('px', ''));
}
```

##### wrap
Wrap an HTML structure around each element in the set of matched elements.
```js
wrap(className) {
  this.each((el) => {
    const wrapper = document.createElement('div');
    wrapper.className = className;
    el.parentNode.insertBefore(wrapper, el);
    wrapper.appendChild(el);
  });
  return this;
}
```

#### Browser support - IE 11+
