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

    • 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

  5. 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

Markdown is supported in the comment area, so you can write inline code in backticks like `this` or multiline blocks of code in in triple backtick fences like this:

```
<div>Example code</div>
```

You don't need to escape code in backticks, Markdown does that for you. If anything screws up, contact us and we can fix it up for you.

*May or may not contain any actual "CSS" or "Tricks".