LoginSignup
1

More than 3 years have passed since last update.

【JavaScript】jQueryっぽく使う

Last updated at Posted at 2019-06-03

appendTo

if(Element.prototype.appendTo === undefined){
    Element.prototype.appendTo = function(el){
        document.querySelector(el).appendChild(this);
    };
}

prependChild

if(Element.prototype.prependChild === undefined){
    Element.prototype.prependChild = function(el){
        this.insertBefore(el, this.firstChild)
    };
}

parent

if(Element.prototype.parent === undefined){
    Element.prototype.parent = function(){
        return this.parentNode;
    };
}

eq

if(Element.prototype.eq === undefined){
    Element.prototype.eq = function(n){
        return this[n];
    };
}

matches

if (!Element.prototype.matches){
    Element.prototype.matches = Element.prototype.msMatchesSelector || Element.prototype.webkitMatchesSelector;
}

closest

if (!Element.prototype.closest) {
    Element.prototype.closest = function(s) {
        var el = this;
        if (!document.documentElement.contains(el)) return null;
        do {
            if (el.matches(s)) return el;
            el = el.parentElement || el.parentNode;
        } while (el !== null && el.nodeType === 1);
        return null;
    };
}

position

if (!Element.prototype.position) {
    Element.prototype.position = function(s) {
        var el = this;
        return {
            left: el.offsetLeft,
            top: el.offsetTop
        };
    };
}

addClass

if (!Element.prototype.addClass) {
    Element.prototype.addClass = function(str) {
        var el = this;
        el.classList.add(str);
    };
}

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
What you can do with signing up
1