Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
137
rated 0 times [  139] [ 2]  / answers: 1 / hits: 18348  / 13 Years ago, thu, august 4, 2011, 12:00:00

I'm lead to this question when trying to figure out the difference between jQuery's .get() and .index(), I've looked over the jQuery API and I still don't get what the difference is between them, maybe i'm not understanding the terminology?



What's the difference between a jQuery object and a DOM element? And are a DOM element and a DOM node the same thing? Are they just <div> and <a> etc. is a DOM node/DOM element just an HTML tag?



EDIT: and isn't the DOM just the structure of the page? <html><body>etc.</body></html>?


More From » jquery

 Answers
15

The get method is used to access the DOM elements within a jQuery object:



var allDivs = $(div).get();


In that example, allDivs will be an array containing all the matched elements (in this case, it would contain every div element in the DOM).



The index method returns an integer that tells you the position of the selected element relative to its siblings. Consider the following HTML:



<ul>
<li>1</li>
<li id=second>2</li>
<li>3</li>
</ul>


And the following jQuery:



console.log($(#second).index()) //Prints 1


As for your other question, a DOM node is pretty much anything in the DOM. Elements are types of nodes (type 1). You also have, for example, text nodes (type 3). An element is pretty much any tag.



To make that clearer, consider the following HTML:



<div id=example>
Some text
<div>Another div</div>
<!--A comment-->
</div>


And the following JS:



var div = $(#example).get(0);
for(var i = 0; i < div.childNodes.length; i++) {
console.log(div.childNodes[i].nodeType);
}


That will print out:



3 - Text node (Some text)
1 - Element node (div)
3 - Text node (Another div)
8 - Comment node (<!-- -->)
3 - Text node (A comment)


You can find a list of node types here. For an excellent introduction to what the DOM actually is, see this MDN article


[#90822] Wednesday, August 3, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kaleyv

Total Points: 259
Total Questions: 99
Total Answers: 107

Location: Saint Helena
Member since Tue, Nov 3, 2020
4 Years ago
;