0

I am reading some code and trying to replicate the same at my end step by step.

I am attaching an event to a particular button and onclick it should log a statement.

Following is the code that does not work :-

(function(){

var el = function(element){
    if(element.charAt['0'] === '#'){
        return document.querySelector(element);
    }
    return document.querySelectorAll(element);
}

var viewer = el('#viewer');
var clear = el('#clear');

console.log(clear);

 var clearAll = function(){
    console.log('Clearing');
 };

//click event
clear.onclick = clearAll;

})();

Above a function is used to get elements.

The below code works

document.getElementById('clear').onclick = clearAll;

or

document.querySelector('#clear').onclick = clearAll;

I do not understand why the above code does not work. Please Help.

Delapouite
  • 9,469
  • 5
  • 36
  • 41
Stacy J
  • 2,721
  • 15
  • 58
  • 92
  • 1
    A function which sometimes returns an element and sometimes returns a node list is likely to be confusing. I don't recommend doing that. – Quentin Mar 07 '17 at 20:46

2 Answers2

1

"foo".charAt['0'] is undefined because charAt is a function and doesn't have a 0 property.

You need () (to call the function), not [] (to access properties of the object).

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

You are using charAt as an array while it is a function.

var el = function(element){
    if(element.charAt('0') === '#'){
        return document.querySelector(element);
    }
    return document.querySelectorAll(element);
}

See it working https://jsfiddle.net/

Regards,

cnexans
  • 975
  • 1
  • 7
  • 20