views:

126

answers:

2

Background: I've created an online circuit design application where .draggable() div tags are containers that contain smaller div containers and so forth.

Question: For any particular div tag I need to quickly identify if it contains other div tags (that may in turn contain other div tags).

--> Since the div tags are draggable, in the DOM they are NOT nested inside each other but I think are absolutely positioned.

So I think that a "hit testing" approach is the only way to determine containment, unless there is some "secret" routine built-in somewhere that could help with this.

I've searched JQuery and I don't see any built-in routine for this. Does anyone know of an algorithm that's quicker than O(n^2)?

Seems like I have to walk the list of div tags in an outer loop (n) and have an inner loop (another n) to compare against all other div tags and do a "containment test" (position, width, height), building a list of contained div tags. That's n-squared. Then I have to build a list of all nested div tags by concatenating contained lists. So the total would be O(n^2)+n.

There must be a better way?

A: 
$.contains(DivContainer, LookForThisDiv);

example:

jQuery.contains(document.documentElement, document.body); // true

doc:

$.contains()

EDIT ok, its pretty much useless if those divs are not nested (just read that) anyway, it's a nice utility function.

jAndy
A: 

I would use jQuery "droppable" as well, in addition to "draggable".

This way you can know where you drop something, and can relocate the item in the DOM accordingly..

Have a look at jQuery draggable + droppable: how to snap dropped element to dropped-on element (explains how to remove the dropped element from its original place and add it to the drop target)

Gaby