2

In this markup, I need to replace the label text "E-mail" with "User Name". I only have access via jQuery.

    <div class="foo" style="border:1px solid #444">
          <span class="field-with-fancyplaceholder">
          <label class="placeholder" for="pseudonym_session_unique_id" style="font-size: 13px;">
          <span>Email</span>
          </label>
          <input id="pseudonym_session_unique_id" class="text" type="text" size="30" name="pseudonym_session[unique_id]">
</span>
          <span class="field-with-fancyplaceholder">
          <label class="placeholder" for="pseudonym_session_password" style="font-size: 13px;">
          <span>Password</span>
          </label>
          <input id="pseudonym_session_password" class="text" type="password" size="30" name="pseudonym_session[password]">
          </span>
        </div>

When I try this

$('label:nth-of-type(1)').addClass('bar');  
$('.bar span').text('user name'); 
// because $('label:nth-of-type(1) span') doesn't work 

both labels get selected and both spans say "user name." How can I get just the first one?

Here's the fiddle.

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
nathanbweb
  • 717
  • 1
  • 11
  • 26
  • 2
    Be careful, as jQuery doesn't actually support `:nth-of-type()`, see http://stackoverflow.com/questions/11745274/what-css3-selectors-does-jquery-really-support-e-g-nth-last-child and http://stackoverflow.com/questions/2093355/nth-of-type-in-jquery-sizzle Although it works in your case, it only does because jQuery is letting the browser handle the selection. Not that this has anything to do with the question itself, but just thought I'd mention it. – BoltClock Aug 17 '12 at 17:36

4 Answers4

4

The labels don't have the same parent element, and :nth-of-type is based on siblings (elements with the same parent).

Note: :nth-of-type is not being implemented by jQuery in browsers that don't natively support it, meaning it won't work in IE6 7 or 8.

Kevin B
  • 94,570
  • 16
  • 163
  • 180
3

You can try the :contains selector:

$('.foo label span:contains("Email")').text('user name');
Ram
  • 143,282
  • 16
  • 168
  • 197
3

You can more reliably select the correct element by more specific attributes:

$("[for=pseudonym_session_unique_id] > span").text("user name");
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
2

Use :eq.

$('label:eq(0) span').text('user name');​

Fiddle.

Cat
  • 66,919
  • 24
  • 133
  • 141