Kuttan Sujith
Kuttan Sujith

Reputation: 7979

use first-Child with $(this)

$(this):first-child is the wrong syntax

I didn't know how to use first-child with $(this) in a .each loop.

Upvotes: 1

Views: 274

Answers (4)

user492203
user492203

Reputation:

You can do that with .find().

HTML

<div id='myDiv'>
    <p>hello</p>
    <p>world</p>
</div>

JavaScript

$('#myDiv').each(function() {
    alert($(this).find(':first-child').text());
});

jQuery :first-child in .each() loop - jsFiddle

Upvotes: 0

Jerome WAGNER
Jerome WAGNER

Reputation: 22422

you should try

$(':first-child', this)

see this example on jsbin

Upvotes: 3

falstro
falstro

Reputation: 35667

I assume 'this' is not a JQuery object, but a DOM-object, wouldn't this do what you want?

this.childNodes[0]

This will also return text-nodes, don't know if JQuery does that.

That said, if you only want the first 'div' child child nodes of nodes with myClass class, do your .each loop differently

$(".myClass > div:fist-child").each(function() {...})

Upvotes: 0

Andrew Marshall
Andrew Marshall

Reputation: 96934

This may work, but I'm not sure if the order is guaranteed:

$(this).children()[0];

Upvotes: 0

Related Questions