Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should i wrap a DOM object with $()?

Tags:

jquery

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?

like image 1000
Orson Avatar asked Dec 09 '09 14:12

Orson


People also ask

How do you wrap an element in Javascript?

querySelector('selector'); // wrapping the event form in a row divWrapper = document. createElement('div'); divWrapper. className = 'row'; wrap_single(elementToWrap, divWrapper);

What is wrap in Javascript?

The wrap() method wraps specified HTML element(s) around each selected element.

What does the jQuery wrap () function do?

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.

How do you wrap two divs?

use Jquery . wrapAll() - It wraps the html structure around all the matched elements.


2 Answers

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:

  1. Events - In any event you bind (like click) in jQuery, the this variable and all the event arguments will reference DOM objects (not jQuery objects).
  2. Non-jQuery javascript - If you have parts of your code that still use 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].

like image 24
fyjham Avatar answered Sep 22 '22 20:09

fyjham


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.

like image 193
kgiannakakis Avatar answered Sep 20 '22 20:09

kgiannakakis