0

I'm trying to make a function that works like this:

JavaScript:

let elm = document.querySelector('section')
elm.gridify();

assuming the function gridify adds display: grid; to the element.

My question is: is that possible and, if so, how?

I tried this, and it's actually working:

function gridify() {
  this.gridify = function(element) {
    let myElement = document.querySelector(element)

    myElement.setAttribute('style', 'display: grid;')
    console.log(myElement);
  }
}

var test = new gridify();
test.gridify('section');

Now, what I want is to make something like what I wrote above.

David Thomas
  • 249,100
  • 51
  • 377
  • 410
  • "*Is that possible*" - yes. "*...and if so, how?*" - where did you get stuck? What did you attempt? I'd suggest using the approach `gridify(elm)`, rather than modifying the prototype (though it is certainly possible, and quite easy, to modify that prototype with another method if you specifically want to). – David Thomas Jul 16 '22 at 13:03
  • You need to define a method in the `HTMLElement` prototype. – Barmar Jul 16 '22 at 13:03

1 Answers1

0

First of all you have to know that edit prototype is something you should never use, but this is the only way to add a custom method to HTMLElement objects (in your case) :

HTMLElement.prototype.gridify = function() { this.style.display = "grid" };

let div = document.querySelector('#myDiv');
div.gridify();

console.log(div.style.display);
// Output
// grid

As suggested in the comments use a function gridify which takes your HTMLElementas parameter is a better practice ;)

function gridify(element) {
    element.style.display = "grid";
}

gridify(div);

console.log(div.style.display);
// Output
// grid
nem0z
  • 1,060
  • 1
  • 4
  • 17
  • @emmanuel-cartelli if you need more explaination to understand my code feel free to ask ;) – nem0z Jul 16 '22 at 13:16
  • 1
    Thank you so much. That was THE answer i was looking for. I do understand your code (thx btw). But i have one question. You said that i should **NEVER** use the HTMLElement prototype. Why ? Is it about security ? – F A T H O M S Jul 16 '22 at 13:24
  • It's not only about `HTMLElement`, in generale you should never edit any `Object.prototype`. Just concidere it's not a good practice. If you want to learn more about this check this post : https://stackoverflow.com/questions/6223449/why-is-it-frowned-upon-to-modify-javascript-objects-prototypes – nem0z Jul 16 '22 at 13:28
  • No probleme ! ;) – nem0z Jul 16 '22 at 13:30