Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select label by nth-of-type

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.

like image 339
nathanbweb Avatar asked Dec 18 '25 18:12

nathanbweb


2 Answers

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.

like image 166
Kevin B Avatar answered Dec 21 '25 12:12

Kevin B


You can try the :contains selector:

$('.foo label span:contains("Email")').text('user name');
like image 31
undefined Avatar answered Dec 21 '25 12:12

undefined