treehouse : what would you like to learn today?
Web Design Web Development iOS Development

Check if Element is inside Another Specific Element

Last updated on:

Replace the first selector with the child you are testing and the second selector with the parent you are testing for.

if ( $(".child-element").parents("#main-nav").length == 1 ) { 

   // YES, the child element is inside the parent

} else {
 
   // NO, it is not inside

}
View Comments

Comments

  1. Joberror
    Permalink to comment#

    Thanks! Clean and Short

  2. Another way ! ?
    Permalink to comment#

    if($(' #childElementID' parentElementId).length == 1) {        // YES, the child element is inside the parent    } else {       // NO, it is not inside    }


    Using jQuery context !

    • Another way ! ?
      Permalink to comment#

      missing the coma sorry !

      if($(' #childElementID'  ,  parentElementId).length == 1) {        // YES, the child element is inside the parent    } else {       // NO, it is not inside    }

  3. Hey Chris! thanks for this…! my method was only detecting the first parent and not the ancestors :(

  4. Permalink to comment#

    if($(“.parentElement”).has(“.childClass”).length)){
    //do something
    }
    else{
    //do something
    }

Leave a Comment

Use markdown or basic HTML and be nice.