How to add extension methods to dom elements

I have elements that I receive this way

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

      

or

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

      

what i want to do is

    elem.myExtensionMethod();

      

or

    elems.myExtensionMethod();

      

My extension method could, as I expected, implement this way

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

      

How do I do this extending dom elements in javascript?

Thank.

+3


source to share


2 answers


You are looking at prototyping HTMLElement

and NodeList

accordingly.

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 red!"
}
      

<p id="p1">This is a plain old paragraph</p>

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

Run codeHide result


+2


source


Thus, elements inherit from Element

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

      



Not recommended because of "browsers" - the best approach is to use some sort of wrapper object that contains a link to your element, and has extension methods, this way kan elements are kept "as is" by different browsers and you still link on them. It's not as bad as it used to be, though

+2


source







All Articles