kumo99
kumo99

Reputation: 133

Add title attribute value from a corresponding heading using jquery

I have a tabs menu with the following structure:

<ul class="tabs-menu">
    <li>
        <a data-href="tab-0">Link</a>
    </li>
    <li>
        <a data-href="tab-1">Link</a>
    </li>
    <li>
        <a data-href="tab-2">Link</a>
    </li>
</ul>
<ul class="tabs-content">
    <li data-href="tab-0" class="active">
        <h2>Title 1</h2>
    </li>
    <li data-href="tab-1" class="">
        <h2>Title 2</h2>
    </li>
    <li data-href="tab-2" class="">
        <h2>Title 3</h2>
    </li>
</ul>

I want to use jquery to add a title attribute to each menu anchor tag, but with the value of the heading h2 under the corresponding tab. For example the first anchor tag in the tabs menu should look like this:

<a data-href="tab-0" title="Title 1">Link</a>

I know some jquery and I thought about using the .each function but I need help in this case.

Thanks

Upvotes: 0

Views: 370

Answers (1)

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67217

Try,

var anchors = $('.tabs-menu a');
var headers = $('.tabs-content :header');

anchors.each(function(i,_){
  $(this).attr('title',headers.eq(i).text());
});

DEMO

Or simply use the .attr()'s receiver function,

anchors.attr('title',function(i,_){ 
   return headers.eq(i).text(); 
});

DEMO

Upvotes: 2

Related Questions