views:

297

answers:

1

This is a kind of a random thing I need. Basically my setup is something like this:

<div class="classname">
  <h3>
     <a class="anchor_classname" title="some_title">..</a>
  </h3>
</div>

The above html segment gets repeated on the page for all existing records.

What I need to do is this: using Jquery, I want to grab the tooltip text from the nested anchor (i.e. "some_title") and set this text to the 'title' attribute of the containing div. I need this to be done for all records where each title text is unique. Is this possible with the setup I've shown or would I need some unique identifiers to distinguish between records? Could someone describe how to accomplish this with jquery? Thanks.

Update: using David's suggestion I managed to use his code and change it slightly as follows:

    $('a.anchor_classname').each(function () {
      var title = $(this).attr("title"); //line 1
      var div = this.parentNode.parentNode; //line 2
      div.title = title; //line 3
    })

How can I convert line 2 and 3 to strictly use jquery functions like parent() and attr(). (It works as it is but I assume it would be better practice to use the standard jquery functions for compliance).

+2  A: 

Duplicating information in this way strikes me as something that is likely to be harmful to accessibility (or at least irritating to screen reader users), and providing effects better achieved by styling the link to fill the h3 and the h3 to fill the div.

That said, this untested code will probably do the job:

jQuery('div.classname > h3 > a.anchor_classname').each(function () {
  var title = this.title;
  var div = this.parentNode.parentNode;
  div.title = title;
})

Or the slower, less efficient, jQuery-where-native-DOM-would-do approach:

jQuery('div.classname > h3 > a.anchor_classname').each(function () {
  var jq = jQuery(this);
  var title = jq.attr('title');
  var div = jq.parent().parent();
  div.attr('title', title);
})
David Dorward
Thanks this worked. Is there any to convert this with the standard jquery functions like parent() and attr()? I managed to change the first line to: var title = $(this).attr("title"); and it worked. But I had no success changing the last two.
es11
haha..love the sarcasm. Thanks for your help..I may end up sticking with the faster-DOM-approach unless someone can convince me otherwise.
es11