开发者

use first-Child with $(this)

开发者 https://www.devze.com 2023-02-11 15:04 出处:网络
$(this):first-child is the wr开发者_运维技巧ong syntax I didn\'t know how to use first-child with $(this) in a .each loop.you should try

$(this):first-child is the wr开发者_运维技巧ong syntax

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


you should try

$(':first-child', this)

see this example on jsbin


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


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

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


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() {...})
0

精彩评论

暂无评论...
验证码 换一张
取 消