jQuery object and DOM element

Viewed 71171

I would like to understand relationship between jQuery object and DOM element..

When jQuery returns an element it shows up as [object Object] in an alert. When getElementByID returns an element it shows up as [object HTMLDivElement]. What does that mean exactly? I mean are both of them objects with a difference ?

Also what methods can operate on jQuery object vs DOM element? Can a single jQuery object represent multiple DOM elements ?

6 Answers

Besides what has been mentioned, I'd like to add something about why jQuery object is imported according to description from jquery-object

  • Compatibility

The implementation of element methods varies across browser vendors and versions.

As an example, set innerHTML of element may not work in most versions of Internet Explorer.

You can set innerHTML in jQuery way and jQuery will help you hide the differences of browser.

// Setting the inner HTML with jQuery.

var target = document.getElementById( "target" );

$( target ).html( "<td>Hello <b>World</b>!</td>" );
  • Convenience

jQuery provides a list of methods bound to jQuery object to smooth developer's experience, please check some of them under http://api.jquery.com/. The website also provides a common DOM manipulation, let's see how to insert an element stored in newElement after the target element in both way.

The DOM way,

// Inserting a new element after another with the native DOM API.

var target = document.getElementById( "target" );

var newElement = document.createElement( "div" );

target.parentNode.insertBefore( newElement, target.nextSibling );

The jQuery way,

// Inserting a new element after another with jQuery.

var target = document.getElementById( "target" );

var newElement = document.createElement( "div" );

$( target ).after( newElement );

Hope this is a supplement.

Related