Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the difference between jquery selectors and js selectors?

Simple question for a noob. Is there a difference between these to variables?

var object1 = document.getElementById('myElement');
var object2 = $('#myElement');

Also, am I able to run normal js stuff on object2? For example, if #myElement is a <textarea> can I do:

object2.value = "fill in with this text";

or, must I do:

$(object2).val('fill in with this text');

or, is there yet a better way?

like image 516
johnnietheblack Avatar asked Dec 09 '10 17:12

johnnietheblack


People also ask

What is difference between jQuery and JavaScript?

JavaScript is an independent language and can exist on its own. JQuery is a JavaScript library. It would not have been invented had JavaScript was not there. jQuery is still dependent on JavaScript as it has to be converted to JavaScript for the browser in-built JavaScript engine to interpret and run it.

Are jQuery selectors the same as CSS selectors?

In jQuery, the class and ID selectors are the same as in CSS. If you want to select elements with a certain class, use a dot ( . ) and the class name. If you want to select elements with a certain ID, use the hash symbol ( # ) and the ID name.

What is a jQuery selector?

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

var object1 = document.getElementById('myElement');

You get a DOM element object from this call. Thus, you use the value property to give it a value.

object1.value = "text";

var object2 = $('#myElement');

You get a jQuery object from this call. Inside the jQuery object is a DOM object. Think of the jQuery object as a wrapper for the DOM object. Diagrammatically it looks something like this (simplified):

jQuery ------------------+
|                        |
| Array ---------------+ |
| |                    | |
| | HTMLElement------+ | |
| | |                | | |
| | | DOM properties | | |
| | | DOM element    | | |
| | |     methods    | | |
| | |                | | |
| | +----------------+ | |
| | there may be zero, | |
| | one or more such   | |
| | objects inside     | |
| +--------------------+ |
| jQuery properties      |
| jQuery methods         |
|                        |
+------------------------+

Since object2 is a jQuery object, you use the val() function to give it a value. You cannot use the value property because it's not the same as a DOM object.

object2.val("text");

Like the other answers say, you can access the underlying DOM object using array dereferencing (object2[0]) or the get() function, then giving it a value using value.

like image 90
BoltClock Avatar answered Nov 15 '22 15:11

BoltClock