0

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?

1
  • If you want a jQuery like method, study the jQuery source code Commented Dec 27, 2014 at 4:40

1 Answer 1

2

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>

Sign up to request clarification or add additional context in comments.

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.