jQuery select or hide deeply nested div within a div with a class

3k views Asked by At

I'm looking to hide a deeply nested div (with a class or ID name) within a container div with only class name. The container div is generated by an application so I cannot set an ID on it. I don't know exactly how many levels the div is generated so I cannot use a path - because that path sometimes changes depending on the page generated. It's almost that I need to use a loop or something.

Here's what I have

<div class ="container">
   <div class ="level1">
     <div class = "level2">
        <other nested  divs and html here...>
                 <div class = "levelN" id="idLevelN">
                      content to hide 
                         <more divs and html here..../>

                 </div>
        </other nested  divs and html here...>
     </div>
   </div>
</div>

I want to hide the div with class = "levelN" id="idLevelN".

I tried all kinds of things but I give up. I tried to use find(), filter(), etc... Help? Thanks

3

There are 3 answers

2
Mark C. On BEST ANSWER

You can use the .children() selector to filter all elements that are children of your selected element.

You can also use .parents() to check the div with the container class is valid (is a parent).

Like:

   if ($( '#idLevelN' ).parents('.container').length){
     $( '#idLevelN').children().hide();
}

Here's a Fiddle

2
Royi Namir On

I'm looking to hide a deeply nested div (with a class or ID name) within a container div with only class name.I don't know exactly how many levels the div is generated

Assuming you have this :

<div id="SearchHere">
  <div>
    <div>
      <div></div>
    </div>
  </div>
  <div></div>
  <div>
    <div>
      <div>
        <div >aaaaa</div> /* you want this*/
      </div>
    </div>
  </div>
  <div>
    <div></div>
  </div>
</div>

Then you can do this :

jQuery.fn.deepestDiv = function()
 {
     var $target = this.children(),
         $next = $target;
     while ($next.length)
     {
         $target = $next;
         $next = $next.children();
     }
     return $target;
 }

Now :

  $("#SearchHere").deepestDiv().css('color','red')

enter image description here

http://jsbin.com/kedobuyumo/3/edit

1
Guy Royse On

You should be able to just access this by ID since IDs are unique for a page.

$('#idLevelN').hide()

However, I realize that in practice this is not always the case so you might need to use the class instead.

$('div.container div.levelN').hide()