wintersylf
wintersylf

Reputation: 177

first-of-type - how does it work?

I have a structure something like the following:

<div>
    <input type="radio" value="A" />
    <input type="radio" value="B" />
</div>
<div>
    <input type="radio" value="C" />
    <input type="radio" value="D" />
</div>

and I want to pick up the first radio button within each div, so I do this:

$('div :radio:first-of-type')

which brings me back AC... however, I recently needed to mark up one of the radio buttons like this:

<div>
  <input type="radio">C
  <span><input type="radio">D</span>
</div>

and now the reference brings me back the ACD. so I have two questions:

1) why does this happen i.e. how exactly does this work? and 2) how can I make the code bring me back only AC as before?

here's a JsFiddle that demonstrates the problem: http://jsfiddle.net/kh3js9ts/

thanks in advance

Upvotes: 1

Views: 57

Answers (2)

Amir
Amir

Reputation: 486

Per jQuery's documentation, "The :first-of-type selector matches elements that have no other element with both the same parent and the same element name coming before it in the document tree."

Given

<span><input type="radio">D</span>

it's clear to see that there are no other elements with both the same parent (span) and same element name (input) in the document tree.

Would the following work for you? This should output AC

$('.not').find(':radio:first').each(function() { s += $(this).val(); });

I have forked a new fiddle

Upvotes: 1

Felix Kling
Felix Kling

Reputation: 816840

Quoting MDN:

The :first-of-type CSS pseudo-class represents the first sibling of its type in the list of children of its parent element.

D is the only child of its parent element, the span.

You could solve that by explicitly asking for the children of the div:

$('div > :radio:first-of-type')

Upvotes: 1

Related Questions