Lee Price
Lee Price

Reputation: 5212

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

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.

Upvotes: 8

Views: 9561

Answers (3)

Felix Kling
Felix Kling

Reputation: 816790

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

Upvotes: 8

Russ Cam
Russ Cam

Reputation: 125528

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.

Upvotes: 6

user196106
user196106

Reputation:

Try this:

$('.parent *:first-child')

Upvotes: 0

Related Questions