Treehouse: Grow your CSS skills. Land your dream job.

Last updated on:

Check if Element is inside Another Specific Element

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

}

Comments

  1. Olivuar Shy
    Permalink to comment#
  2. Joberror
    Permalink to comment#

    Thanks! Clean and Short

  3. 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    }

  4. Sumeet Chawla
    Permalink to comment#

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

  5. sajay
    Permalink to comment#

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

    • Kevin REdman

      99% of the time, there is NO need for else. Simply a break or a continue.

      If (!negatedCondition) {
      // do some logic
      // return/continue/nothing
      }

      // do some logic
      return

    • tony
      Permalink to comment#

      thanks sajay . I am finding this

  6. JasonHuang
    Permalink to comment#

    just use the method in jquery ,
    $.contains(param1,param2);
    param1 is the container which also called parent , this param must be a DOM element .
    param2 is the element contained by the containner .

    this method could find out the container-contained relationship weather it’s the direct child of nested more deeply .

Leave a Comment

Posting Code

We highly encourage you to post problematic HTML/CSS/JavaScript over on CodePen and include the link in your post. It's much easier to see, understand, and help with when you do that.

Markdown is supported, so you can write inline code like `<div>this</div>` or multiline blocks of code in in triple backtick fences like this:

```
<script>
  function example() {
    element.innerHTML = "<div>code</div>";
  }
</script>
```