Alexander
Alexander

Reputation: 1829

How do I add extension methods in dom elements

I have elements I get this way

    var elem = document.getElementById('my-element');

or

    var elems = document.querySelector('.all-elements-with-this-class');

what I want to do is this

    elem.myExtensionMethod();

or

    elems.myExtensionMethod();

My extension method might, as I have imagined, would be implemented this way

    var myExtensionMethod = function() {
        this.classList.add('add-this-class-to-all');
    }

How do I do this extending dom elements in javascript?

Thanks.

Upvotes: 3

Views: 1375

Answers (2)

BobbyTables
BobbyTables

Reputation: 4695

Like this, the elements inherit from Element

Element.prototype.myExtensionMethod = function() {
    console.log("myExtensionMethod!", this);
};

Its not recommended because of "browsers" - a better approach is to use some kind of wrapping object that holds a reference to your element, and has the extension methods, that way the elements kan be kept "as is" by the various browsers, and you kan still reference them. Its not as bad as it used to be though

Upvotes: 2

Phil
Phil

Reputation: 164897

You're looking at adding to the HTMLElement and NodeList prototypes, respectively.

For example

HTMLElement.prototype.myExtensionMethod = function() {
  this.classList.add('add-this-class-to-all');
}
NodeList.prototype.myExtensionMethod = function() {
  this.forEach(el => el.myExtensionMethod())
}

document.getElementById('p1').myExtensionMethod()
document.querySelectorAll('li').myExtensionMethod();
.add-this-class-to-all {
  background-color: red;
  color: white;
}
.add-this-class-to-all:after {
  content: " but now it's red!"
}
<p id="p1">This is a plain old paragraph</p>

<ul>
<li>List #1</li>
<li>List #2</li>
</ul>

Upvotes: 3

Related Questions