Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery selectors don't work for assigning dom element to variable

Tags:

jquery

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?

like image 888
user1469779 Avatar asked Apr 02 '13 13:04

user1469779


People also ask

Can jQuery selector be a variable?

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.

What is $() in jQuery?

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)

How do jQuery selectors work?

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.


1 Answers

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
like image 92
Alnitak Avatar answered Sep 19 '22 01:09

Alnitak