Adam Oates Adam Oates - 1 year ago 71
Javascript Question

How would I go about make function for object JavaScript?

How would I making my own function like

? For example it would look something like

Answer Source

You would need to modify the HTMLElement prototype.

document.getElementById will return a HTMLElement object, however it is generally thought of as bad practice modifying any native object as they are subject to change and you might have issue in different browsers. And you might need different handling for different elements.

(function(proto) {
  // HTMLelement prototype is passed into the closure
  // set your method if it's not set on the prototype
  proto.myFunction = proto.myFunction || function() {
    // this === element that method was run on
    console.log('myFunction', this.textContent)

var element = document.getElementById('element')
<div id="element">this is my element</div>

If you ever want to have a method. I would suggest using jQuery and creating a simple plugin to attach new behaviour, You will also get the benefit of being able to work with collections of elements, and have the jQuery api as helper functions.

  // jQuery is passed into the closure
  // $.fn === $.prototype === jQuery.prototype
  $.fn.myFunction = function(){
    // this === the element that the method was run on

var $element = $('#element')
<script src=""></script>
<div id="element">this is my $element</div>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download