tags:

views:

76

answers:

3

I was writing some code in jQuery, like:

$(".middleContent").not(this).slideUp();

(this = currently active .middleContent element)

And I was wondering how JavaScript knew the elements index in the DOM.

I know each object is unique, but if you have a few elements with the same class how does it distinguish between them? It is to do which its index in the tree of all the elements, like how a program has an address in RAM?

+2  A: 

Each dom element is an individual object and unique. The not does comparisons on the current execution context ( this ) to make sure that any element inside the array doesnt equal this.

meder
+1  A: 

The elements in the DOM are just objects themselves, organised into a tree structure, so they have next and previous siblings at the same level, their own list of children, a parent. From this you can walk around the structure of the tree and manipulate it.

You can obtain the object(s) inside a jQuery object by using indexing notation:

var caption = $('#caption');
var domElement = caption[0];

Then domElement will contain one of these.

Daniel Earwicker
+1  A: 

I think you're underestimating what it means for a DOM element to be unique. It's not only the class, tag name or index within the current parent element that identifies a DOM element. Each DOM element internally has a unique identifier, which is not accessible to you. It's used by the browser to organize the DOM internally. There can be hundreds of seemingly identical <div class="middleContent" /> elements in your page, each single one has a unique internal identifier. If you compare one DOM element to another, the browser will always be able to tell whether it's the same element or one that just looks like it.

this refers to one specific DOM element, therefore jQuery is able to filter it out of a collection of seemingly similar elements.

deceze