1

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

3
  • JQuery defines the variable $, so when you do var $ = ... you're overwriting jQuery's definition. Your append function only works because this is the window. Commented Oct 31, 2016 at 23:36
  • @Tibrogargan He's not trying to use jQuery, he's trying to implement something similar. Commented Oct 31, 2016 at 23:37
  • You're creating separate functions called append() and empty(), so they will not be available by chaining them from the $ variable. In other words, you can't do $.empty because empty is not part of the $ variable. Commented Oct 31, 2016 at 23:37

1 Answer 1

6

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 ( ) { 

      },
    };
};
Sign up to request clarification or add additional context in comments.

2 Comments

When I tried the .append() I was excited because I thought I did something right, guess not. Thanks for your help
@bena Sorry for the letdown, but better to find out now than later. If you want to continue "messing around" with the code in my answer, you could switch from querySelectorAll to var object = querySelector (to only select one object) and then use object.innerHTML to implement your own append. You could also add a console.log in the function to confirm that it is your own append being used and not the built-in one.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.