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

  • Use Markdown, and it will escape the code for you, like `<div class="cool">`.
  • Use triple-backticks for blocks of code.
    ``` 
    <div>
      <h1>multi-line block of code</h1>
      <span>be cool yo.</span>
    </div>
    ```
  • Otherwise, escape your code, like <code>&lt;div class="cool"&gt;</code>. Markdown is just easier though.

Current ye@r *

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