ben a ben a - 1 month ago 7
Javascript Question

Functions in javascript

I am new to javascript and I was messing around with it. I was checking out jquery and I wanted to see if I could create something to do the same things. This is my js file

//returns a dom
var $ = function(selector) {
return document.querySelector(selector);
};
//adds something to the dom
var append = function(value) {
this.innerHTML += value;
};
//clears dom
var empty = function() {
while (this.lastChild) this.removeChild(this.lastChild);
};


When I call
$('#test')
I get the dom with id test. When I call
$('#test').append('hi there')
it works. However when I try
$('#test').empty()
I get a
Uncaught TypeError: $(...).empty is not a function
Any idea why? If I am doing something comletely wrong please let me know. Thanks

Answer

Your functions aren't added to the prototype chain of DOM elements, (that wouldn't be a good idea), so they can't be called as methods of DOM elements.

append works, because the DOM node already had a method called append, and it has nothing to do with the function you stored in a variable called append.

jQuery works by creating a container object that holds a collection of DOM elements and has it's own methods. EG:

 var $ = function(selector) {
    var objects = document.querySelectorAll(selector);
    return {
      append: function ( ) { 
        // do something to `objects` here
      },
      empty: function ( ) { 

      },
    };
};