0

I am trying to make my own version of jQuery. I am using this code so far, to test my selectors:

js(".hide");

function js(selector){
    var applyTo = document.querySelector(selector);
    applyTo.style.color = 'red';
}

However, this does not work, and the error console said:
Uncaught TypeError: Cannot read property 'style' of null Why is applyTo null?

yaakov
  • 4,568
  • 4
  • 27
  • 51
  • 3
    Do you have any elements with the class `hide`? - If so, is this code running before the DOM is loaded? – tymeJV Aug 18 '15 at 18:03
  • 1
    I realize that what your doing is for learning purposes, as opposed to reinventing the wheel, but man, that's a big project. Have you considered just taking an existing library and adding stuff to it? – durbnpoisn Aug 18 '15 at 18:04
  • 1
    @tymeJV, Thanks. It was running before the dom was loaded – yaakov Aug 18 '15 at 18:06
  • @durbnpoisn, I am doing this for the challenge. So far it's been quite a big one :)) – yaakov Aug 18 '15 at 18:06
  • Note that [Document.querySelector](https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector) doesn't work in IE < 8 so you might want to use a [polyfill](https://gist.github.com/chrisjlee/8960575). – KVM Aug 18 '15 at 18:07

1 Answers1

-1

To make it not fail in case the selector doesn't get you any element:

function js(selector){
    var applyTo = document.querySelector(selector);
    if(applyTo) { applyTo.style.color = 'red'; }
}

Make sure it's called only after the DOM has loaded.

connexo
  • 53,704
  • 14
  • 91
  • 128