Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if an element is a child of a parent

People also ask

Which element is the parent and which is the child?

A parent is an element that is directly above and connected to an element in the document tree. In the diagram below, the <div> is a parent to the <ul>. A child is an element that is directly below and connected to an element in the document tree.

How do you check if an element is in another element?

contains() method checks if an element is inside another, and returns a boolean: true if it is, and false if it's not. Call it on the parent element, and pass the element you want to check for in as an argument.

Which Javascript function is used to select the child tag from the parent element?

getElementById('element-id') .


If you are only interested in the direct parent, and not other ancestors, you can just use parent(), and give it the selector, as in target.parent('div#hello').

Example: http://jsfiddle.net/6BX9n/

function fun(evt) {
    var target = $(evt.target);    
    if (target.parent('div#hello').length) {
        alert('Your clicked element is having div#hello as parent');
    }
}

Or if you want to check to see if there are any ancestors that match, then use .parents().

Example: http://jsfiddle.net/6BX9n/1/

function fun(evt) {
    var target = $(evt.target);    
    if (target.parents('div#hello').length) {
        alert('Your clicked element is having div#hello as parent');
    }
}

.has() seems to be designed for this purpose. Since it returns a jQuery object, you have to test for .length as well:

if ($('div#hello').has(target).length) {
   alert('Target is a child of #hello');
}

Vanilla 1-liner for IE8+:

parent !== child && parent.contains(child);

Here, how it works:

function contains(parent, child) {
  return parent !== child && parent.contains(child);
}

var parentEl = document.querySelector('#parent'),
    childEl = document.querySelector('#child')
    
if (contains(parentEl, childEl)) {
  document.querySelector('#result').innerText = 'I confirm, that child is within parent el';
}

if (!contains(childEl, parentEl)) {
  document.querySelector('#result').innerText += ' and parent is not within child';
}
<div id="parent">
  <div>
    <table>
      <tr>
        <td><span id="child"></span></td>
      </tr>
    </table>
  </div>
</div>
<div id="result"></div>

If you have an element that does not have a specific selector and you still want to check if it is a descendant of another element, you can use jQuery.contains()

jQuery.contains( container, contained )
Description: Check to see if a DOM element is a descendant of another DOM element.

You can pass the parent element and the element that you want to check to that function and it returns if the latter is a descendant of the first.