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