Adam Oates Adam Oates - 2 months ago 10
Javascript Question

How would I go about make function for object JavaScript?

How would I making my own function like

.innerHTML
for
document.getElementById("idName");
? For example it would look something like
document.getElementById("idName").myFunction;
.

Answer

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)
  }
})(HTMLElement.prototype)

var element = document.getElementById('element')
element.myFunction()
<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.

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

var $element = $('#element')
$element.myFunction()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="element">this is my $element</div>