The Wayback Machine - https://web.archive.org/web/20240825154413/https://www.geeksforgeeks.org/how-to-set-dom-element-as-first-child/
Open In App

How to set DOM Element as First Child ?

Last Updated : 21 Sep, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In this article, we will explore different approaches to setting a DOM element as the first child of its parent. When working with HTML documents, it is common to manipulate the DOM (Document Object Model) to rearrange elements dynamically, Setting a DOM element as the first child means inserting it at the beginning of its parent’s list of children elements.

There are several methods that can be used to set the DOM element as the first child.

We will explore all the above methods along with their basic implementation with the help of examples.

Approach 1: Using insertBefore()

In this approach we are using the insertBefore() method, the insertBefore() method in HTML DOM is used to insert a new node before the existing node as specified by the user.

Syntax:

parentElement.insertBefore(newChild, parentElement.firstChild);

Example: In this example, we use the insertBefore() method to insert the newly created paragraph element (newChild) as the first child of the parent (parentElement).

HTML




<!DOCTYPE html>
<html>
  
<head>
    <title>Set DOM Element as First Child</title>
</head>
  
<body>
    <div id="parent">
        <p>Existing Child 1</p>
        <p>Existing Child 2</p>
    </div>
  
    <script>
        const parentElement =
            document.getElementById("parent");
        const newChild =
            document.createElement("p");
        newChild.textContent = "New First Child";
  
        parentElement.insertBefore(
            newChild, parentElement.firstChild);
    </script>
</body>
  
</html>


Output:

12

Approach 2: Using prepend()

In this approach we are using the jQuery prepend() method, the prepend() method is an inbuilt method in jQuery that is used to insert specified content at the beginning of the selected element.

Syntax:

$(selector).prepend(content, function)

Example: In this example, we utilize jQuery’s prepend() method to directly add the newChild element as the first child of the parent with the ID “parent.”

HTML




<!DOCTYPE html>
<html>
  
<head>
    <title>Set DOM Element as First Child</title>
    <script src=
    </script>
</head>
  
<body>
    <div id="parent">
        <p>Existing Child 1</p>
        <p>Existing Child 2</p>
    </div>
  
    <script>
        const newChild = document.createElement("p");
        newChild.textContent = "New First Child";
  
        $(document).ready(function () {
            $("#parent").prepend(newChild);
        });
    </script>
</body>
  
</html>


Output:

12



Similar Reads

Difference between :first-child and :first-of-type selector in CSS
The :first-child and :first-of-type selectors in CSS are used to target specific child elements within a parent. The :first-child selector targets an element if it is the first child of its parent, regardless of type. On the other hand, the :first-of-type selector targets the first occurrence of a specified element type within its parent. Understan
2 min read
How to apply styles only to the first child of an element using CSS ?
The :first-child selector is a pseudo-class in CSS that enables you to target the initial child element within a parent container. This selector handpicks elements that are the first immediate child of their parent. It serves as a powerful selector that makes it easier to apply unique styles or modifications to that specific element. &lt;div class=
1 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 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 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
Replace a DOM element with another DOM element in place
The task is to replace an element by another element in place using JavaScript. Below are the few methods: parentNode Property: This property returns the parent node of the defined node, as a Node object. Syntax: node.parentNode Return value: It returns a node object, which represents the parent node of a node, or null if there is no parent. replac
3 min read
Remove all the child elements of a DOM node in JavaScript
Child elements are the nested elements in the HTML and we have to remove them. To remove the elements in HTML we need to use DOM methods. There are so many ways to remove the child elements of a DOM node: Table of Content Using removeChild()Using innerHTML propertyUsing removeChild()In this approach, we are using the HTML DOM removeChild() method,
2 min read
How to use a not:first-child selector in CSS?
This selector is used to select every element which is not the first-child of its parent element. It is represented as an argument in the form of :not(first-child) element. Syntax: :not( element ) { // CSS property } Example: &lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;not first child selector&lt;/title&gt; &lt;style&gt; h1 { color
1 min read
CSS :first-child Selector
The :first-child selector is used to select those elements which are the first-child elements. For :first-child selector the &lt;!DOCTYPE&gt; must be declared for IE8 and earlier versions. Syntax: :first-child { /* CSS property */}Example 1: C/C++ Code &lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;first child selector&lt;/title&gt;
1 min read
jQuery :first-child Selector
jQuery :first-child Selector is used to select every element that is the first child of its parent element. Syntax: $("selector:first-child")It selects and returns the first child element of its parent element. Example 1: In this example, we select the first paragraph element and set its background color to green. C/C++ Code &lt;!DOCTYPE html&gt;
1 min read
What is first child in CSS ?
In CSS, the :first-child selector is used to target the first child element within its parent. It applies styles to the first element only if it is the first child of its parent, allowing for specific formatting and design changes. Syntax: :first-child { //property}Example: Here is the demonstration of the first child in CSS. [GFGTABS] HTML &lt;!DO
1 min read
How to count child element using jQuery ?
It is very simple to count the number of child elements in the HTML file using jQuery. For example: If you have a parent element consisting of many children elements then you can use .length or.children().length method as given below. Syntax: var len=$("#parentID").length; or var count = $("#parentId").children().length; Example 1: &lt;!DOCTYPE htm
1 min read
How to select all children of an element except the last child using CSS?
When designing and developing web applications, sometimes we need to select all the child elements of an element except the last element. To select all the children of an element except the last child, use :not and :last-child pseudo classes. Syntax: element:not(:last-child) { // CSS Style } Example 1: This example creates a navigation menu separat
2 min read
How to count all child elements of a particular element using JavaScript ?
Given an HTML document containing some elements nested elements and the task is to count all the child elements of a particular element. It is very simple to count the number of child elements of a particular element using JavaScript. For example: If you have a parent element consisting of many child elements then you can use HTML DOM childElementC
1 min read
How to apply css property to a child element using JQuery?
The task is to apply CSS property to a child element using jQuery. To do that, first we select the child element with the help of children() method in jQuery and then apply CSS property to it with the help of css() method in jQuery. Syntax: // Note : children method selects the direct child to parent $(selector).children("selector").css("property-n
2 min read
How to dragleave fired when hovering a child element in HTML 5?
When a div is made draggable and we hover over a div that executes dragenter and dragleave command, we face a problem when there is a child present inside that div which executes the dragleave command as shown below. Example 1: Here when hovered over child color disappears. C/C++ Code &lt;!DOCTYPE html&gt; &lt;html lang=&quot;en&quot;&gt; &lt;head
2 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 apply an id attribute to a child element of a ReactJS component ?
To apply the id attribute to a child element of the React JS component, we can use the React JS states and props. Also, using hooks we can directly access the Dom elements and modify the attributes as required. PrerequisitesReact JSuseState HookuseRef HookTable of Content Passing id as a prop to child componentUsing useRef hookSteps to create React
3 min read
How to get the child element of a parent using JavaScript ?
In this article, we will learn to get the child element of the parent using JavaScript. 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. There are 2 ways to get the child element: Table of Content By using the children propertyBy using the querySelec
3 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
Why to get "Router may have only one child element" warning ?
React Router Dom is a collection of navigational components that compose declaratively with your application. Whether you want to have bookmarkable URLs for your web app or a composable way to navigate in React Native, React Router Dom works in both places. We will be taking into consideration react-router-dom v5.3.0. Prerequisites:NPM &amp; Node.j
4 min read
Run Python script from Node.js using child process spawn() method
Node.js is one of the most adopted web development technologies but it lacks support for machine learning, deep learning and artificial intelligence libraries. Luckily, Python supports all these and many more other features. Django Framework for Python can utilize this functionality of Python and can provide support for building new age web applica
3 min read
CSS :only-child Selector
The:only-child selector in CSS is used to match every element that is the only child of its parent. It represents an element without any siblings. Syntax: :only-child { // CSS property } Example 1: C/C++ Code &lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;:only-child selector&lt;/title&gt; &lt;style&gt; h1 { color: green; text-align:
2 min read
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
jQuery :nth-last-child() Selector
The jQuery :nth-last-child() selector is used to select all elements that are the nth last child of their parent. The counting of elements starts from the last element. Syntax: :nth-last-child( n | even | odd | formula )Parameters: The :nth-last-child() selector contain parameters which are listed below: n: It holds the child index number of the se
2 min read
jQuery :last-child Selector
It is a jQuery Selector used to select every element that is the last child of its parent. Syntax: $(":last-child")Example 1: Here is the basic example of a last-child selector. C/C++ Code &lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;jQuery :last-child Selector&lt;/title&gt; &lt;script src= &quot;https://ajax.googleapis.com/ajax/lib
1 min read
jQuery :only-child Selector
It is a jQuery Selector used to select every element that is the only child of it's parent i.e only a single child is selected. Syntax: $(":only-child")Example 1: In this example, we are using only-child selector. C/C++ Code &lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;jQuery :only-child Selector&lt;/title&gt; &lt;script src= &quot;
1 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
jQuery :nth-child() Selector
The jQuery :nth-child() Selector Selects all elements that are the nth-child of their parent elements. Syntax: $("Selector:nth-child( index | even |odd |equation )")Index: Index provided. Index starts fromeven: even number of child elements get selected.odd: odd number of child elements will get selected.equation: select child elements by solving a
1 min read