In this article, you’ll learn how to get the first child of specific type using JavaScript. Let’s read this article now.
Get the first child of specific type using JavaScript
For simplicity’s sake, the example every solution will be working off of is getting the text of the first child with the H3 tag of this DIV element:
<div id="MyDiv"> <h1>H1-1</h1> <h1>H1-2</h1> <h2>H3-1</h2> <h3>H3-1</h3> <h3>H3-2</h3> </div>
Using .children()
and .first()
(JQuery)
Remember: If you are dealing with HTML DOM Elements in JavaScript, use JQuery.
JQuery is a JavaScript library specialized in traversal and manipulation of HTML DOM elements for animations, event handling and Ajax.
The fundamental method use in every JQuery selection is the JQuery Selector ("$()")
which takes in a CSS selector (which will be explained a bit further in the next method), though you only need to understand 3 selectors for this:
- Blank: Selects all elements with the specified tags.
"#"
: Selects all elements with the specified ID."."
: Selects all elements with the specified class.
The next two functions needed are .children()
and .first()
, which is actually very simple and self-explanatory. .children()
returns a collection of child elements and .first()
returns the first instance of that list.
For example:
function getFirstChildOfTag(tag, parentId) { const parent = $("#" + parentId); // Get Parent Element const children = parent.children(tag); // Get List of Children with tag const firstChild = children.first(); // Get the First Child of List return firstChild; }; // Return the text if the Element is not null console.log(getFirstChildOfTag("h3", "MyDiv")?.innerHTML);
Output:
"H3-1"
A thing to note is that the JQuery selectors returns an JQuery
object; although if you are already using JQuery, you won’t need to worry about it too much.
Using the document.querySelector()
function (JavaScript)
The document.querySelector()
function finds an element that matches a specific CSS selector – which is a pattern of keywords used to detect an HTML Element. This article will not be covering CSS selectors in heavy detail, though the CSS selector used will be described.
For example:
function getFirstChildOfTag(tag, parentId) { const selectorString = `#${parentId}>${tag}:first-of-type`; // CSS Selector String return document.querySelector(selectorString); // Get the Child by that Selector }; // Return the text if the Element is not null console.log(getFirstChildOfTag("h3", "MyDiv")?.innerHTML);
Output:
"H3-1"
The CSS selector when simplified could be viewed as: "[ID]>[TAG]:first-of-type"
; note that in the explanation below, "a"
and "b"
represents HTML Elements.
"a>b"
:a
is the parent ofb
"a:first-of-type"
: Get the first instance of taga
Using Element.children
and Element.tagName
(JavaScript)
Probably the one you will be using if you’re not intending to use JQuery or you specifically need to get the HTMLElement
class (which we’ll get to in the next solution).
The idea is to get all the children of an element with the read-only .children
property; then iterate over it until an element with the correct tag is found (which you can find via the .tagName
property).
For example:
function getFirstChildOfTag(tag, parentId) { var parent = document.getElementById(parentId); // Get Parent for (const curElm of parent.children) { if (curElm.tagName.toLowerCase() === tag) { // If the current Element of the list has the specified Tag return curElm; // The first Element to have that tag is the First Child } } return null; // If none of the Children has the tag, return null }; // Return the text if the Element is not null console.log(getFirstChildOfTag("h3", "MyDiv")?.innerHTML);
Output:
"H3-1"
Some things to note: The .children
property returns an HTMLCollection
, which is a collection of HTMLElements
(which is a class representing an HTML element and is inherited from the Element
class) and importantly: is not an array but is similar to one. Therefore, both an HTMLCollection
and an array share some things like being able to access values using the accessor ([index])
; However, the HTMLCollection
class does not have a .forEach()
function, though it is still possible to iterate over the class with the of keyword – which is used in the example above.
Additionally, a small quirk with the .tagName
property is that it is always displayed in all-caps; therefore you might want to convert it to lower-case using the String class’ .toLowerCase()
function.
Using Node.childNodes
and Node.nodeName
(JavaScript)
This method is not actually that different practically from the method above besides different names and the fact that the return value would be a Node instead of an HTMLElement
.
A Node
is the abstract definition of what a DOM element is, what it does and its properties. It is the base for several other DOM classes such as Text
, Comment
or Element
– which is the base for the HTMLElement
. You can find a more detailed documentation here.
Here’s the solution:
Code:
function getFirstChildOfTag(tag, parentId) { var parent = document.getElementById(parentId); // Get Parent for (const curNode of parent.childNodes) { if (curNode.nodeName.toLowerCase() === tag) { // If the current Element of the list has the specified Tag return curNode; // The first Element to have that tag is the First Child } } return null; // If none of the Children has the tag, return null }; // Return the text if the Element is not null console.log(getFirstChildOfTag("h3", "MyDiv")?.textContent);
Output:
"H3-1"
If you find this a little difficult to understand, all you need to know is that in this context the .childNodes
and .nodeName
are the same as the .children and .tagName
properties respectively.
Summary
To get the first child of specific type using JavaScript, you can use JQuery’s method; However, if you don’t want to use JQuery, the solution might depend on whether you want to return an HTMLElement
object or an Node
object by using the 2nd and 3rd method or the 4th method respectively.
Maybe you are interested:

Hello, my name is Davis Cole. I love learning and sharing knowledge about programming languages. Some of my strengths are Java, HTML, CSS, JavaScript, C#,… I believe my articles about them will help you a lot.
Programming Languages: Java, HTML, CSS, JavaScript, C#, ASP.NET, SQL, PHP