How would I making my own function like .innerHTML for document.getElementById("idName");? For example it would look something like document.getElementById("idName").myFunction;.
2 Answers
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>
Comments
Here is how you would go about this:
To create a new method for a object such as a string, you can just do String.prototype.MethodName = function(args) { code }.
Here is an example:
String.prototype.replaceAll = function(a, b) {
var regExp
regExp = new RegExp(a, "ig")
return this.replace(regExp, b)
}
g = "Hello null"
console.log(g)
g = g.replaceAll("null", "World!")
console.log(g)
In this example, we created the replaceAll function. It is used to replace
a certain keyword with a certain word or phrase. Once we do that, we can call the replaceAll function on a String.
Hope this helps!
object.Prototype.methodName = function(){...}or add it directlyobject.methodName = function(){...}. This is a duplicate, see the link below..innerHTMLisn't a function. Are you asking how to add a function to all DOM elements, so that you could then saydocument.getElementById("anyElementId").myFunction()? Or do you want your function to be available only for one specific DOM element?