tags:

views:

146

answers:

2

I have an unordered list like this:

<div class="blueBoxMid">
  <ul>
    <li>First item <em>This is the hover text</em></li>
    <li>Second item <em>This is the hover text</em></li>
  </ul>
</div>

I want to use jQuery to generate this:

<div class="blueBoxMid">
  <ul>
    <li title="This is the hover text">First item</li>
    <li title="This is the hover text">Second item</li>
  </ul>
</div>

My current code looks liket his, but I couldn't get it to work. Help anyone? :)

$('.blueBoxMid li').each(function(){
  $('.blueBoxMid li em').hide();
  $('.blueBoxMid li').attr('title', $(this).children('em').text()).hover(function(){$(this).css('cursor', 'help')});
});
+3  A: 

Try something like this:

$('div.blueBoxMid ul li').each(function () {
    var tooltip = $(this).children('em').remove().text();
    $(this).attr('title', tooltip).css('cursor', 'help');
});

Basically, it loops through every <li> element, removes its <em> element and gets the text contents of the <em> element, then it applies the title attribute and CSS style. The CSS style can be on always (not only on hover) since it will only change the cursor when hovered anyways.

Blixt
I figured out by myself, but the code looks the same as this, although I use $(this).children('em').hide() instead of remove().
rebellion
Okay. `remove()` can be considered more efficient, since the element is removed from the DOM instead of being styled away with CSS. Also, if you are still using `hover()`, remove that since it may cause some discrepancies the first time the element is hovered, and after that all hovers would just make unnecessary calls that do nothing to the CSS (since it's already set to "help" after the first call.)
Blixt
Thanks, switched out hide() with remove() :)
rebellion
+1  A: 

jQuery sometimes struggles to get the attributes of hidden elements, so try setting the title of the li element before hiding the em element.

Note that the $('.blueBoxMid li em') and $('.blueBoxMid li') within your each() function still refer to all elements matching those criteria; use $(this) to refer to each one in turn. If you want to hide all the '.blueBoxMid li em' elements, your line $('.blueBoxMid li em').hide(); doesn't need to be within an each loop.

Waggers