Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find out what's the first child tag name?

Tags:

jquery

I need to find what the first child of an element is.

For example:

<div class="parent">
    <div class="child"></div>
    <img class="child" />
    <div class="child"></div>
</div>

In this example the FIRST child is a div.

Another example:

<div class="parent">
    <img class="child" />
    <img class="child" />
    <div class="child"></div>
</div>

In this example the first child is a img.

like image 654
Lee Price Avatar asked Oct 29 '11 14:10

Lee Price


People also ask

What is first child in HTML?

Definition and UsageThe firstChild property returns the first child node of a node. The firstChild property returns a node object. The firstChild property is read-only. The firstChild property is the same as childNodes[0] .

How do I access my first child in CSS?

The :first-child selector is used to select the specified selector, only if it is the first child of its parent.


2 Answers

Yet another one:

var tag = $('.parent').children().get(0).nodeName;

Or if you already have any other reference to the parent element, you can simply access its children property (assuming it is a DOM node, not a jQuery object):

var tag = parent.children[0].nodeName;

Reference: .children(), .get(), Element.children, Node.nodeName

like image 90
Felix Kling Avatar answered Oct 02 '22 07:10

Felix Kling


This would be one way

$('div.parent').children(':first');

If you want to know what type of element it is

$('div.parent').children(':first')[0].nodeName;

The [0] will get the first underlying DOM element in the wrapped set.

like image 22
Russ Cam Avatar answered Oct 02 '22 07:10

Russ Cam