views:

78

answers:

2

Background: I've created an online circuit design application where 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).

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?

+1  A: 

You can do the following checks

$('div_selector').has('div').length > 0 // it contains divs

alternatively

$('div_selector').is(':has(div)') // returns true if it contains divs

the above checks work for actual containment (nesting) in the dom (not for visual containment where the dimensions of one div are contained in the other).

Gaby
(I actually asked the wrong question. I created a new question regarding draggable div tags.)
Pete Alvin
+1  A: 

You don't even need jQuery. You can just do this test, where "div" is the container:

if (div.getElementsByTagName('div').length > 0) {
  // do something
}
Robusto
Thank you. I wish I could give "credit" for more than one correct answer in this system. (I actually asked the wrong question. I created a new question regarding draggable div tags.)
Pete Alvin