Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting between a jQuery object and a pure js object?

What is the difference between the object returned by $('#elementID') and the object returned by document.getElementById('elementID')?

Moreover, how can you easily convert from one to the other? For instance:

$('a').each(function(){
    // How can I access 'this' as a pure javascript object instead of as a jQuery object?
});

This has plagued me for some time now. I know you shouldn't mix the two, really, but I just want to understand the principle.

like image 639
temporary_user_name Avatar asked Oct 12 '13 23:10

temporary_user_name


People also ask

What will you use in jQuery if you wanted to convert the contents of a form elements into string for submission?

What will you use in jQuery if you wanted to convert the contents of a form element into string for submission? You can do this: var frm = $(document. myform); var data = JSON. stringify(frm.

Can I use instead of jQuery?

Nevertheless, Native javascript is one of the best jQuery alternatives, in fact, It is the framework of JS. Javascript is the best because any browsers ships with javascript and you do not need to install jQuery in your application.

Which method returns the element as a jQuery object?

get()Returns: Array. Description: Retrieve the elements matched by the jQuery object.

What's a jQuery object?

A jQuery object is created from the array elements in the order they appeared in the array; unlike most other multi-element jQuery operations, the elements are not sorted in DOM order. Elements will be copied from the array as-is and won't be unwrapped if they're already jQuery collections.


1 Answers

What is the difference between the object returned by $('#elementID') and the object returned by document.getElementById('elementID')?

$('#elementID') returns an object with a ton of functions that all operate on the result of document.getElementById('elementID'). Think of the jQuery object like a giant robot that document.getElementById('elementID') is sitting inside of.

You can access the wrapped DOM object with:

  • $('#elementID').get()
  • $('#elementID').get(0)
  • $('#elementID')[0]

If there's more than one element matched by the selector, you can access, for example, the second element with $elements.get(1) or $elements[1].

Moreover, how can you easily convert from one to the other?

To wrap an object with jQuery's convenience functions, just pass it into the $ function:

$(document.getElementById('foo'))
$(document.querySelectorAll('.foo:not(.bar)'))

To go the other way, use .get() or the bracket notation.

In your specific example, you don't need to do anything special because this is actually a normal DOM object. This is why you often see callbacks littered with $(this).

like image 126
Blender Avatar answered Sep 23 '22 22:09

Blender