The Wayback Machine - https://web.archive.org/web/20240909211653/https://www.geeksforgeeks.org/how-to-get-the-child-element-of-a-parent-using-javascript/
Open In App

How to get the child element of a parent using JavaScript ?

Last Updated : 09 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given an HTML document, the task is to select a particular element and get all the child elements of the parent element with the help of JavaScript.

Below are the approaches to get the child element of a parent using JavaScript:

By using the children property

  • The DOM children property is used to return an HTML collection of all the child elements of the specified element. 
  • Select an element whose child element is going to be selected.
  • Use .children property to get access to all the children of the element.
  • Select the particular child based on the index.

Example: This example implements the .children property to get the HTML collection of all the child elements of the specified element.

HTML
<!DOCTYPE HTML>
<html>

<head>
    <title>
        Finding child element of parent
        with pure JavaScript
    </title>

    <style>
        .parent {
            background: green;
            color: white;
        }

        .child {
            background: blue;
            color: white;
            margin: 10px;
        }
    </style>
</head>

<body style="text-align:center;">
    <h1 style="color:green;">
        GeeksforGeeks
    </h1>

    <h3>
        Click on the button select the child node
    </h3>

    <div class="parent" id="parent">
        Parent
        <div class="child"> Child </div>
    </div>
    <br>

    <button onclick="GFG_Fun()">
        click here
    </button>

    <h1 id="result" style="color: green;"></h1>

    <script>
        let res = document.getElementById('result');

        function GFG_Fun() {
            parent = document.getElementById('parent');
            children = parent.children[0];
            res.innerHTML = "Text of child node is - '" +
                children.innerHTML + "'";
        }
    </script>
</body>

</html>

Output:

class Property

By using the querySelector Method

  • The querySelector() method in HTML is used to return the first element that matches a specified CSS selector(s) in the document.
  • Select the parent element whose child element is going to be selected.
  • Use .querySelector() method on the parent.
  • Use the className of the child to select that particular child.

Example: This example implements the .querySelector() method to get the first element to match the specified CSS selector(s) in the document.

HTML
<!DOCTYPE HTML>
<html>

<head>
    <title>
        How to get the child element of 
        a parent using JavaScript ?
    </title>

    <style>
        .parent {
            background: green;
            color: white;
        }

        .child1 {
            background: blue;
            color: white;
            margin: 10px;
        }

        .child2 {
            background: red;
            color: white;
            margin: 10px;
        }
    </style>
</head>

<body style="text-align:center;">
    <h1 style="color:green;">
        GeeksforGeeks
    </h1>

    <h3>
        Click on the button select 
        the child node
    </h3>

    <div class="parent" id="parent"> Parent
        <div class="child child1"> Child1 </div>
        <div class="child child2"> Child2 </div>
    </div>
    <br>

    <button onclick="GFG_Fun()"> 
        click here 
    </button>
    
    <h1 id="result" style="color: green;"></h1>

    <script>
        let res = document.getElementById('result');

        function GFG_Fun() {
            let  parent = document.getElementById('parent');
            let children = parent.querySelectorAll('.child');
            res.innerHTML = "Text of child node is - '" + 
                children[0].innerHTML + "' and '" + 
                children[1].innerHTML + "'";
        }
    </script>
</body>

</html>

Output:

.querySelector() Method



Similar Reads

How to force child div to be 100% of parent div's height without specifying parent's height?
When designing a website, you may want to create a layout where a child div element fills up the height of its parent div element. However, you may not know the exact height of the parent div element and you don't want to specify it. In this article, we will explore different approaches to force a child div element to be 100% of its parent div elem
3 min read
How to return true if the parent element contains the child element in JavaScript ?
In JavaScript, children property returns an array of those elements which are children of a given element. In order to check whether the parent element (say x) contains a child element (say y), we can use the children property to get the array of all children of x and then check whether the array obtained contains y. To get the child element of a p
2 min read
How to remove parent element except its child element using jQuery ?
Given an HTML document and the task is to remove the parent element except for its child element. Approach 1: Use contents() method to select all the direct children, including text and comment nodes for the selected element.Selected elements are stored in a variable.Now, use replaceWith() method to replace the content of parent element by its all
2 min read
How to Check if an element is a child of a parent using JavaScript?
In this article, we are going to see the methods by which we can Check if an element is a child of a parent using JavaScript. These are the following methods: Table of Content Using the Node.contains() methodLooping through the parents of the given childUsing the hasChildNodes() methodMethod 1: Using the Node.contains() methodThe Node.contains() me
4 min read
How to Style Parent Element when Hover Over a Child Element in CSS ?
In this article, we will learn how to style the parent element when hovering over a child element. Styling the parent element when hovering over a child element is a useful CSS technique that allows you to change the appearance of the parent element when the mouse cursor is hovering over one of its child elements. This can be useful for adding inte
2 min read
Why margin on child element moves the parent element in CSS ?
In CSS, when a margin is applied to a child element, it can affect the position of the parent element. This happens because the margins of an element collapse with the margins of its adjacent siblings or its parent, based on certain rules. If the parent element has no padding or border, and the child element has a top margin, then the child element
3 min read
How to Make a Child Div Element Wider than Parent Div using CSS ?
When the child div element has a fixed width that is wider than the parent div element, it will display overflow outside of the parent element. Because the overflow is hidden by default, one approach is to utilize the overflow attribute to enable it on an element. Another approach includes setting the position property of the parent div element to
2 min read
How to get Access to a Child Method From the Parent in VueJS ?
When working with Vue.js components, it's common to encounter scenarios where you need to access a method inside the parent component that is defined in a child component. This can be useful for triggering specific actions or updating the child component's state. Below are the methods that can be used to access a child component method from a paren
4 min read
How to call a parent method from child class in JavaScript?
Inheritance in programming allows a class to derive methods and properties from another class, similar to how a child inherits traits from its parents. A child class can have its properties in addition to inherited ones. The deriving class is called a derived, sub, or child class, while the class it derives from is the base, super, or parent class.
3 min read
How to Merge Child Object Value to Parent Key Based on Key Name in JavaScript ?
JavaScript allows us to merge values from child objects into their parent object based on a specific key name. This can be useful for organizing data or simplifying complex structures. There are several approaches available in JavaScript to merge child object values to parent key based on the key name which are as follows. Table of Content Using fo
4 min read
How to apply CSS in last child of parent using jQuery ?
In this article, we will see how to set styles in the last child of the parent element using jQuery. To set the style on the last child of parent, we use jQuery :last-child selector. The :last-child selector is used to select every element that is the last child of its parent element. Syntax: $("Selector:last-child") Approach: First, we create an H
1 min read
How to Call Function Inside Child Component from Parent Component using useRef hook ?
In ReactJS, we can pass the function reference from parent components to child components. However, there are scenarios where you may need to call the function inside the child component from the parent component. It can be done by creating a reference using the useRef hook and createRef method as well. Prerequisites :NPM &amp; Node JSReact JSReact
2 min read
jQuery parent &gt; child Selector
It is a jQuery Selector used to select all elements that are the direct child of its parent element. Syntax: ("parent &gt; child")Parameter Values: parent: Using this, the parent element will be selected.child: Using this, the direct child element of the specified parent element will be selected.Example 1: C/C++ Code &lt;!DOCTYPE html&gt; &lt;html
1 min read
How to communicate from parent component to the child component in Angular 9 ?
Angular makes the communication between components very easy. In this article, we will learn how to communicate from a parent component to the child component. Approach: Let's create two components: parent child In the parent component, declare the property that you want to receive in the child component, say 'ParentId'. While including the child c
2 min read
How to navigate to a parent route from a child route?
In angular, a root component that serves as the parent component of all the components and the rest of the other components can be called a Child Component to the root component. This structure is in a form of a tree where a component that is the parent of a child lies above the child component and this there is no direct link between them but in g
4 min read
How to expand floated child div's height to its parent's height in CSS ?
Making the height of the floating child div equal to the height of the parent div is referred to as expanding the height of the floated child div to the height of the parent div. Approach 1: Using the CSS "clearfix" method is the first approach to increase a floated child div's height to match its parent's height. When an element is floated, it is
4 min read
How to make Parent Div Activate Styling of Child Div for Hover and Active ?
In this article, we will see how to make parent div activate styling of child div for hover and active. We can do this by using Pseudo-classes like hover and active. Approaches to make parent div activate styling of child div for hover and activeUsing Pure CSS: with pseudo-classesUsing CSS and JavaScript: without pseudo-classesMethod 1: Using Pure
2 min read
How to pass property from a parent component props to a child component ?
Passing props from parent to child in React JS is an important concept. Props are read-only properties that are sent from the parent components to the child components. We can pass props in from parent to child using React JS functional as well as class components Table of ContentPassing Property Using Class ComponentsPassing Property Using Functio
3 min read
How to Access Child Method From the Parent in VueJS ?
In this article, we are going to discuss how can we access the child method from the parent in VueJS. We need to create such a component that shows the use of accessing the child methods from the parent component. Approach:We will create two components ParentMethod and ChildComponent.ParentMethod vue.js component consists of a parent component whic
3 min read
How does useImperativeHandle help parent and child components communicate?
useImperativeHandle in React allows parent and child components to communicate more effectively by enabling the child component to specify which methods and properties should be accessible to the parent through a ref. How Does It Help:Customized Interaction: Child components can define a specific set of functions or data they want to share with the
2 min read
How to Call Parent Components's Function from Child Component in React ?
In React, it is very important to manage communication between components for building flexible and maintainable applications. Sometime, you need to trigger a function defined in a parent component from a child component. In this article, we'll see how to achieve this in React by passing down functions as props from parent to child components. Tabl
3 min read
Passing data from Child to Parent Component in Angular
In Angular, passing data from a child component to its parent component involves emitting events. Essentially, the child component emits an event containing the data that the parent component needs to receive. This is typically achieved using Angular's EventEmitter class, where the child component emits an event with the data payload, and the paren
3 min read
How to Call a Parent Method from a Child Component in Vue 3 ?
Vue.js is a JavaScript framework for building user interfaces. In Vue 3 parent and child component can communicate with each other through props and events. Props are used to pass the data from the parent to the child component and events are used to pass the data from child to parent component. These are the following approaches: Table of Content
3 min read
Parent to Child Communication with Metadata in Angular 17
A parent component in Angular can transfer data or information to its child components using parent-to-child communication. This is an essential component of creating reusable and modular Angular applications. This is an overview of Angular 17's parent-to-child communication features. PrerequisitesBasic JavaScriptBasic AngularWhat is Parent to Chil
2 min read
How to apply style to parent if it has child with CSS?
While we are familiar with applying styles to child elements when a parent class is present, sometimes we need to apply styles to a parent element based on its child elements. Although CSS does not natively support parent selectors, there are ways to achieve similar effects using combinators and JavaScript. Understanding Child CombinatorsA child co
2 min read
How to access index of the parent ng-repeat from child ng-repeat in AngularJS ?
In this article, we will see How to access the index of the parent ng-repeat from child ng-repeat in AngularJS. In AngularJS applications, when we implement the nested ng-repeat directives and if we need to access the index of the parent ng-repeat from the child ng-repeat, then we can do this by using 2 different approaches like by using the $paren
6 min read
How to pass data from Parent to Child component in Angular ?
We can use the @Input directive for passing the data from the Parent to Child component in Angular Using Input Binding: @Input - We can use this directive inside the child component to access the data sent by the parent component. Here app.component is the Parent component and cdetail.component is the child component. Parent Componentapp.component.
3 min read
How To Share Data Between Child And Parent Directives And Components In Angular?
Sharing data between child and parent components in Angular is important for building dynamic and interactive applications. This can be done through various concepts, including input and output bindings or using a shared service. This article will explore how to use an Angular service to enable data communication, allowing both parent and child com
5 min read
How to Pass Data from Child Component to its Parent in ReactJS ?
To pass the data from child to parent we will utilize the react's unidirectional data flow. it means data is passed from parent components to child components. Here instead of passing data to child we will pass a function that sends the data back to the parent. ApproachTo pass data from the child to the parent component: Define Callback: First, cre
2 min read
How to get position of an element relative to the document or parent using jQuery ?
In order to get the location of an element relative to the document, jQuery offset() method is used. The offset() method is an inbuilt method in jQuery which is used to set or returns the offset coordinates of the selected element. We can also use the jQuery position() method. The position() method is an inbuilt method in jQuery which is used to fi
2 min read