Grabbing the childrens of an ID

Hey,

I have this code running:


$('body').live('click', function (event) {
    if (event.target.id != 'GlobalList' && event.target.id != 'ajaxList')
      $('#ajaxList').hide();
  });

The problem I’m having is that id GlobalList has CSS childs and when I click within the DIV if its not GlobalList then it closes out.

I’m trying to see how I can modify it, so it won’t close if I click within the DIV structure

Here is the HTML


<div class="globalList" id="ajaxList">
  <div class="globalListNew"><a href="#" id="globalListNewListLink">Create List</a></div>
  <div class="globalListNewListContainer" id="globalListNewListContainer">
    <input type="text" class="globalListInput" maxlength="100" />
    <input type="submit" value="Add" class="globalListAddInput" />
  </div>
  <span id="loadingTxt">Loading List...</span>
  <div id="ajaxAllLists">
    <div class="globalListContainer"></div>
  </div>
</div>

For example if I click on the href it closes the DIV out.

Any trick to go around this? thanks :slight_smile:

You could check to see if the event target element is a descendant ajaxList.
maybe something like
$(“#ajaxList”).has(event.target).length === 1
or
$(event.target).parents(“#ajaxList”).length === 1
or
$(event.target, “#ajaxList”).length === 1

alternatively, you could add a click event handler on on ajaxList, which will call event.stopPropagation(), preventing the click event from bubbling up to the body.

Looks like I’m gonna go with the $(event.target).parents(“#ajaxList”).length === 1 method. thanks

That reminds me, do you happen to know if a way to get the first DIV (i guess grand parent?) of the structure.

Right now what I’m doing in certain situations is that if I need to traverse up I just do $(this).parent() or $(this).parent().parent(). What i’m trying to do is not have to repeat myself so many times. It would be a pain if I’m trying to traverse all the way out to the first DIV if I have to do $(this).parent().parent().parent()…etc…

I looked up the API of jquery but didnt find anything relative close to it.

closest() traverses up through direct ancestors until the selector matches.

There’s also plain old javascript too, this.parentNode.parentNode…