How to Add My Own Methods to HTMLelement Object

How to add my own methods to HTMLElement object?

Although you can prototype on the HTMLElement in many browsers - Internet Explorer (6,7,8) is NOT one of them. AFAIK, IE9 does support this (though I haven't tested it).

For browsers that do handle it, you can do:

HTMLElement.prototype.doHello = function(thing){
console.log(this + ' says: ' + thing)
}

document.body.doHello('hello')

How do I (and should I) make additional methods on DOM objects?

If you want to be able to call custom methods on an instance which alters a DOM element, it would probably make the most sense to have the class just save the DOM element as a property of the instance, and then look it up when necessary. For example:

class MyElement {
constructor(element) {
this.element = element;
}
triggerDisplay() {
const { element } = this;
if (element.style.display === 'none') element.style.display = null;
else element.style.display = 'none';
}
}

const myCustomElement = new MyElement(document.getElementById('myDiv'));

myCustomElement.triggerDisplay();

If you need to be able to directly reference element properties without going through the .element property, you can use prototypal inheritence to set the element as the internal prototype of the instance:

const customProps = {
triggerDisplay: {
value: function() {
const element = Object.getPrototypeOf(this);
if (element.style.display === 'none') element.style.display = null;
else element.style.display = 'none';
}
}
};
const makeCustomElement = (element) => {
return Object.create(element, customProps);
};

const myCustomElement = makeCustomElement(document.getElementById('myDiv'));

myCustomElement.triggerDisplay();

(if you also want to assign to properties directly on the myCustomElement, then use another Object.create wrapper so that assignment does not mutate the customProps object)

Invoke a custom method on a DOM element

You do not need to use jQuery. You can use document.getElementById('MyObject') to get a reference to the DOM node.

To run your doSomething function on it, you would need to add a node parameter to it something like this:

function doSomething(input) {
// do something with input DOM element
}

doSomething(document.getElementById('MyObject'));

To have it chained, you would need to add to the Element interface which all DOM nodes implement (rereading, I meant inherit from). If you go that way, you could do:

Element.prototype.doSomething = function() {
alert(this);
}

document.getElementById('MyObject').doSomething();

JSFiddle: http://jsfiddle.net/6Lyb4b9p/

MDN: getElementById

JavaScript: Best way to add custom properties/methods to built-in objects (e.g. arrays)

Method 1 and Method 3 do the same thing. You're just defining functions against an instantiated array. If you're after speed simply stick with methods 1 or 3. Turns out classes extended from array and prototypes from arrays (which is the same thing under the hood) are simply very slow when it comes to large volumes of data. Small cases it's probably fine. I can't seem to find much info on this subject myself either. But hopefully this is a good starting point for further testing. It could take 10ish seconds to complete the test so be patient...

//Method 1
let myArray1 = [];
myArray1.unique = () => [...new Set(myArray1)];
myArray1.last = () => myArray1.at(-1);
//Method 2
class superArray extends Array {
constructor(...items) { super(...items) }
unique(){return [...new Set(this)]}
last(){ return this.at(-1)}
}
let myArray2 = new superArray();
//Method 3
let superArrayMethods = {
unique: function(){return [...new Set(this)]},
last: function(){return this.at(-1)}
}
let myArray3 = [];
myArray3 = Object.assign(myArray3, superArrayMethods);
//Method 4
let superArrayPrototype = {
unique: function(){return [...new Set(this)]},
last: function(){return this.at(-1)}
}
Object.setPrototypeOf(superArrayPrototype,Array.prototype);
let myArray4 = [];
Object.setPrototypeOf(myArray4,superArrayPrototype);

//Timers
console.time("myArray1")
for(i=0; i<10000000; i++) { myArray1.push(i); }
console.timeEnd("myArray1")

console.time("myArray2")
for(i=0; i<10000000; i++) { myArray2.push(i); }
console.timeEnd("myArray2")

console.time("myArray3")
for(i=0; i<10000000; i++) { myArray3.push(i); }
console.timeEnd("myArray3")

console.time("myArray4")
for(i=0; i<10000000; i++) { myArray4.push(i); }
console.timeEnd("myArray4")

console.time("unique myArray1")
myArray1.unique();
console.timeEnd("unique myArray1")

console.time("unique myArray2")
myArray2.unique();
console.timeEnd("unique myArray2")

console.time("unique myArray3")
myArray3.unique();
console.timeEnd("unique myArray3")

console.time("unique myArray4")
myArray4.unique();
console.timeEnd("unique myArray4")

How to add my own methods to HTMLElement object?

Although you can prototype on the HTMLElement in many browsers - Internet Explorer (6,7,8) is NOT one of them. AFAIK, IE9 does support this (though I haven't tested it).

For browsers that do handle it, you can do:

HTMLElement.prototype.doHello = function(thing){
console.log(this + ' says: ' + thing)
}

document.body.doHello('hello')

Does an HTML element have a prototype (like Element.prototype.myFunc)?

A DOM HTMLElement is an Object so it should work, however, an Object is not necessarily an HTMLElement, so you should add that method to HTMLElement.prototype instead:

HTMLElement.prototype.move = function() {
let position = 0;
const self = this;

function render() {
self.style = `left: ${position++}px`;
requestAnimationFrame(render);
}

requestAnimationFrame(render);
}

document.getElementById('square').move();
#square {
position: fixed;
height: 20px;
width: 20px;
background-color: blue;
}
<div id="square">
</div>

How do you create a method for a custom object in JavaScript?

var newObj = {
met1 : function () {
alert('hello');
}
};

Then, the method can be called like such :

newObj.met1();

Btw, when declaring a new object, use the object literal ({}), not the new Object() constructor.



Related Topics



Leave a reply



Submit