简体   繁体   中英

How to create jQuery like object functions with JavaScript

I'm working on trying to create a small library of helper functions for a project.

At the moment, I've setup a lot of functions in global scope that look like this:

function addClass(el, className) {
   el.classList.add(className);
}

var target = document.querySelector('.target);
addClass(target, "added-class");

With adding a class as an example, I'd like to follow a jQuery like function so that it gets called like this:

var target = document.querySelector('.target);
target.addClass("added-class");

How can I setup a function so that it is called this way?

You could extend HTMLElement

As @charlietfl mentioned, extending native API works fine in theory but should also be concerned that future specifications in HTMLElement could add similar methods that open the app up to potential collisions.

Like this example:

 function addClass(className) { this.classList.add(className); } // here you extends HTMLElement prototype HTMLElement.prototype.addClass = addClass; var target = document.getElementById('mydiv'); target.addClass('red'); var target2 = document.getElementById('mydiv2'); target2.addClass('blue'); 
 .red { background: red; } .blue { background: blue; } 
 <div id="mydiv">HELLO</div> <div id="mydiv2">WORLD</div> 

Or Could use a Wrapper

Like this another example:

 function Element(id) { this.target = document.getElementById(id); this.addClass = function (className) { this.target.classList.add(className); } return this; } var target =new Element('mydiv'); target.addClass('red'); var target2 =new Element('mydiv2'); target2.addClass('blue'); 
 .red { background: red; } .blue { background: blue; } 
 <div id="mydiv">HELLO</div> <div id="mydiv2">WORLD</div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM