Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

CSS jQuery Basics (2014) Creating a Simple Drawing Application Perform: Part 5

Rohit Patwari
Rohit Patwari
5,500 Points

What is the difference between jQuery representation of an Element and javaScript representation . I am little confused

eg :-

$("canvas") and $("canvas")[0]

Whats the conceptual difference . I thought the first one ie $("canvas") is actually represents the html element in the DOM

Isn't that rather an JS question?

2 Answers

Joshua Ferdaszewski
Joshua Ferdaszewski
12,716 Points

The best way to think about a jQuery object is as a wrapper of zero or more DOM elements. It behaves somewhat like an array, but as this documentation says:

Many developers new to jQuery assume that this collection is an array. It has a zero-indexed sequence of DOM elements, some familiar array functions, and a .length property, after all. Actually, the jQuery object is more complicated than that.

As a wrapper, it smooths out some compatibility issues (i.e. IE) and adds convenience methods that help with some of the more cludgy parts of dealing with the DOM. Another important piece is that methods on jQuery objects return jQuery objects. So method calls can be strung together.

I would recommend checking out the above article as well as the jQuery Documentation itself. Good luck with your learning!

The $("canvas") represents an array (jQuery Object) of all objects matched by the selector. $("canvas")[0] represents the first object in that array. Hope that''s understandable.

Rohit Patwari
Rohit Patwari
5,500 Points

Hey Philip ,

Thanks for your reply .

But why dont we follow such a syntax for other things. Suppose I want to grab text of a title element . I would do - $("title").text() , rather than $("title")[0].text();

I think $("p").text() is just the short form. $("p")[1].text(); makes sense when you have multiple paragraph elements.