Niko Kovačič
Niko Kovačič

Reputation: 193

jQuery select first child three levels deep

I have the following HTML structure:

<div class="s1>
 <div class="s2">
  <span class="span1">
    <span>text</span>
  </span>
 </div>
</div>

Currently I am selecting the most nested span with the following selectors:

$(".s1").find(">:first-child").find(">first:child").find(">:first-child")

Is there a more efficient way to select that inner span?

Edit: Div with class s1 is already cached, so I cant use $("selector").

Upvotes: 1

Views: 836

Answers (5)

XML
XML

Reputation: 19498

$('div.s1 > div:first-child > span:first-child > span:first-child')

Do you need anything more specific than that?

Upvotes: -1

MazarD
MazarD

Reputation: 2740

If you are talking about efficiency the fastest is to define an id for the span:

<span id="spanX">text</span>
$('#spanX')

Because this selector maps directly to the cross-browser getElementById

If you cant touch the html for some reason the fastest way would be:

$('.span1 span:first')

Upvotes: 0

Sushanth --
Sushanth --

Reputation: 55750

Give it a class or Id and then try accessing it

 <span id="sp1" class="sp1">text</span>

$('#sp1')  or $('.sp1')

// Or

$('.span1 > span')

Upvotes: 0

bfavaretto
bfavaretto

Reputation: 71918

There are several options, something like this should work:

.s1 .s2 .span1 span:first-child

I'm not sure how specific you need the selector to be.

Upvotes: 1

Adil
Adil

Reputation: 148120

You can access it through span1 class,

$('.span1 span')

Upvotes: 2

Related Questions