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.

1
  • 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. Commented Mar 7, 2017 at 20:46

2 Answers 2

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).

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

1 Comment

Ohhhhh...yes that worked...stupid mistake...Thanks so much
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,

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.