user1338176
user1338176

Reputation: 105

How to get title attribute for each a href and put as span?

Hi I am trying to get the title attribute of each a href in jQuery and put it as a span and have done something like this:

$('.menu li').each(function(){
    var title = $('.menu li a').attr("title");
    $(".menu li a span").text(title);
});

Each link has a different title attribute added too it but its applying the first title attribute to every span, am I missing something?

thanks

Upvotes: 1

Views: 1760

Answers (2)

user229044
user229044

Reputation: 239312

You're selecting every menu's li inside your loop. You want to affect only the <li> within the current .menu:

$('.menu li').each(function(){
  var title = $(this).find("a").attr("title");
  $(this).find("a span").text(title);
});

Upvotes: 2

Adriano Carneiro
Adriano Carneiro

Reputation: 58615

You need to reference the matched element being iterated (a .menu li element) in the each with this keyword:

$(".menu li").each(function(){
    var title = $(this).find("a").attr("title");
    $(this).find("a span").text(title);
});

Upvotes: 1

Related Questions