I have a program that assigns a variable as:
var theList = document.getElementById('theList');
it uses jquery, but if I write it like this:
var theList = $('#theList');
the function that uses that variable doesn't work.
What is the distinction between a jquery selector and using getElementById?
Projects In JavaScript & JQueryYes, it is possible to pass a variable into a jQuery attribute-contains selector. The [attribute*=value] selector is used to select each element with a specific attribute and a value containing a string.
The jQuery syntax is tailor-made for selecting HTML elements and performing some action on the element(s). Basic syntax is: $(selector).action() A $ sign to define/access jQuery. A (selector) to "query (or find)" HTML elements. A jQuery action() to be performed on the element(s)
jQuery selectors allow you to select and manipulate HTML element(s). jQuery selectors are used to "find" (or select) HTML elements based on their name, id, classes, types, attributes, values of attributes and much more. It's based on the existing CSS Selectors, and in addition, it has some own custom selectors.
document.getElementById returns a native DOM Element object, with direct access to that node's properties.
jQuery functions instead return "jQuery collections", i.e a jQuery object with an associated set of functions / plugins, etc that acts like an array of DOM nodes.
A common convention used to tell the former from the latter is to prefix variables containing the latter with $:
To extract the individual elements from a jQuery collection as DOM nodes, either use .get(n) or [n].
var $theList = $('#theList'); // jQuery collection
var theList = $theList[0]; // DOM node
var theList = $theList.get(0); // also a DOM node
Attribute and property access depends on whether you have a jQuery collection or not:
var id = $theList.attr('id'); // jQuery function
var id = theList.id; // native property
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With