Help me understand jquery selectors vs vanilla selectors


I am trying to write more plain JS over jQuery and I have a question. How does jquerys element selectors differ from vanilla JS selectors?

Take this example:

// example one
    var elem = $('.list-item'),
        numb = elem.size();

// example two
    var elem = document.querySelectorAll('.list-item'),
        numb = elem.size();

Example one works, while example two gives me “Uncaught TypeError: elem.size is not a function”. Why is this?

1 Like

By the looks of the jQuery documentation, size() is length


1 Like

well yeah but length gives me the same TypeError.

I thought length was a property and not a method.

Shouldn’t it be

numb = elem.length;

True, thanks for that=)

But further thought, can’t i use jquery methods and functions with JS selectors? changing all my jquery selectors to JS selectors gives me lots of errors in the console. Index(), nex(), last() etc doesnt work and all i did was change $(‘.class’) to document.querySelectorAll(‘.class’)

1 Like

You have to change all the other calls as well. You can’t just change part of the code without changing all of it.

All of those jQuery methods do have equivalent native JavaScript that does the same thing (after all JQuery itself is written in JavaScript).

1 Like

Okey. Well tomorrow I will rewrite all the jQuery to plain JS in this small/medium sized website, should be a good learning experience I guess=)

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.