How to set a label's title based on it's inner HTML?

5.4k Views Asked by At

I have an html form field with lots of checkboxes.

How to set a label's title attbibased on it's inner HTML? I need to do this for all titles.

For example, I need to transform

<div id=field>
  <label class='option'>Ski</label>
  <label class='option'>Hockey</label>
  <label class='option'>Baseball</label>
</div>

to:

<div id=field>
  <label title='Ski' class='option'>Ski</label>
  <label title='Hockey' class='option'>Hockey</label>
  <label title='Baseball' class='option'>Baseball</label>
</div>

I tried the following jQuery code:

$('#field label.option').attr('title',$(this).html());  

but it gives me tons of garbage.

So how to get the value inside each matching label?

This is jQuery 1.4.4.

Please advise.

3

There are 3 best solutions below

0
Bhadra On BEST ANSWER
$('#field label.option').attr('title',function(){ return $(this).text() });
3
BenM On

title attributes should contain text only, so you'd be better to user text():

$('#field label.option').prop('title', function() { return $(this).text(); });

If you absolutely have to set the title to the inner HTML, use html():

$('#field label.option').prop('title', function() { return $(this).html(); });

jsFiddle Demo

0
Dibu On

this may help you

$('.option').each(function(i,lbl)
   {
       $(lbl).attr('title',$(this).html());
   }
);