ArticleZip > Check If Clicked Element Is Descendant Of Parent Otherwise Remove Parent Element

Check If Clicked Element Is Descendant Of Parent Otherwise Remove Parent Element

When working with web development, having the ability to manipulate the elements on a page dynamically can greatly enhance the user experience. One common task is checking if an element is a descendant of another element, and based on that condition, either retaining or removing the parent element. In this article, we will discuss how you can achieve this using JavaScript.

To accomplish this task, we will utilize the `contains` method available in JavaScript. This method can be called on a parent element to check if it contains a specific child element. If the child element is indeed a descendant of the parent, the method will return `true`; otherwise, it will return `false`.

Let's consider a scenario where you have an HTML structure with nested elements like the following:

Html

<div id="parentElement">
    <div class="childElement">
        <p>Sub Element</p>
    </div>
</div>

Now, let's assume that you want to check if a specific element, let's say the paragraph element `

Sub Element

`, is a descendant of the `parentElement`. Here's how you can achieve this in JavaScript:

Javascript

const parentElement = document.getElementById('parentElement');
const childElement = document.querySelector('.childElement');
const subElement = document.querySelector('p');

if (parentElement.contains(subElement)) {
    console.log('The sub element is a descendant of the parent element.');
} else {
    parentElement.remove();
    console.log('The sub element is not a descendant of the parent element. Parent element removed.');
}

In the code snippet above, we first retrieve references to the parent element, child element, and the specific element we want to check for. We then use the `contains` method to check if the `subElement` exists within the `parentElement`. If the check returns `true`, we log a message indicating that the sub element is indeed a descendant. Otherwise, we remove the entire `parentElement` from the DOM.

It's important to note that the `contains` method provides a simple and efficient way to determine the relationship between elements in the DOM tree. By leveraging this method, you can easily perform actions based on whether an element is a descendant or not, thus enabling you to create more interactive and dynamic web experiences for your users.

In conclusion, being able to check if an element is a descendant of another element is a valuable capability in web development. With the `contains` method in JavaScript, you can easily implement logic to handle scenarios where you need to verify and manipulate the relationship between elements on a web page. Incorporate this technique into your projects to enhance the interactivity and functionality of your web applications.

×