Using JQuery:
Sometimes, I can do variable.val()
and it works. Sometimes, I'm required to use $(variable).val()
.
I want to be able to make the choice without trial-and-error.
Does anyone know when to wrap an object with $()
while using JQuery?
querySelector('selector'); // wrapping the event form in a row divWrapper = document. createElement('div'); divWrapper. className = 'row'; wrap_single(elementToWrap, divWrapper);
The wrap() method wraps specified HTML element(s) around each selected element.
jQuery wrap() method is used to wrap specified HTML elements around each selected element. The wrap () function can accept any string or object that could be passed through the $() factory function.
use Jquery . wrapAll() - It wraps the html structure around all the matched elements.
Simply put $(variable)
takes a DOM element and creates a jQuery object. You need to use it any time you end up with a DOM object rather than a jQuery object.
The most likely reasons you'd get a DOM object would be:
this
variable and all the event arguments will reference DOM objects (not jQuery objects).document.getElementById
(Like if you have some legacy javascript or are referencing a third-party library that's not a jQuery plugin for some reason) then these will be DOM objects and need to be wrapped.There is however no harm in calling $(variable)
if variable
is already a jQuery object, beyond the obfuscation to someone who might presume it's a DOM object by how you use it, and you can always get back to the DOM object by calling $(variable)[0]
.
Wrapping a DOM object with $() will convert it to a jQuery Wrapped Set Element. This way you should be able to call jQuery methods with it (val(), attr(), show(), hide(), serialize()).
If however you need to get or set pure javascript properties, then you shouldn't wrap it.
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