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. User Avatar
    Olivuar Shy
    Permalink to comment#
  2. User Avatar
    Joberror
    Permalink to comment#

    Thanks! Clean and Short

  3. User Avatar
    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 !

    • User Avatar
      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. User Avatar
    Sumeet Chawla
    Permalink to comment#

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

  5. User Avatar
    sajay
    Permalink to comment#

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

    • User Avatar
      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

    • User Avatar
      tony
      Permalink to comment#

      thanks sajay . I am finding this

  6. User Avatar
    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 .

Submit a Comment

Posting Code

You may write comments in Markdown. This makes code easy to post, as you can write inline code like `<div>this</div>` or multiline blocks of code in triple backtick fences (```) with double new lines before and after.

Code of Conduct

Absolutely anyone is welcome to submit a comment here. But not all comments will be posted. Think of it like writing a letter to the editor. All submitted comments will be read, but not all published. Published comments will be on-topic, helpful, and further the discussion or debate.

Want to tell us something privately?

Feel free to use our contact form. That's a great place to let us know about typos or anything off-topic.

icon-closeicon-emailicon-linkicon-logo-staricon-menuicon-searchicon-staricon-tag