5

I want to set title text of a link calling a function which receives as parameter the id of the element and outputs the text.

something like

$(a).attr('title', function() {return $(this).id + "foo"});

but a construct like this doesn't exist as far I know. What can I do? Thanks.

1
  • Just a note that prop is recommended over attr in most cases as of jQuery 1.7+ Commented Mar 13, 2012 at 14:48

4 Answers 4

9

Use $(this).attr('id') or this.id. Do not mix them.

$(a).attr('title', function() {return $(this).attr('id') + "foo"});
$(a).attr('title', function() {return this.id + "foo"});        // <-- Preferred
//^ Is this a a variable? If not, you have to quote it: $("a").attr( ... );
Sign up to request clarification or add additional context in comments.

1 Comment

+1. Though there's never really any reason to use $(this).attr('id') - it's longer to type and results in unnecessary function calls.
1
var id = $(this).attr('id') ; //capture the caller 
$(a).attr('title',id + 'foo');

Comments

1

Use jQuery's .each() method:

$('a').each(function(){
    $(this).attr('title', this.id + ' foo');
});

References: jQuery .each()

Comments

0
$('a').each(function(){
    $(this).attr('title', $(this).attr('id'));
});

Maybe?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.