Summer
Summer

Reputation: 2498

Referring to an object's ID in a jQuery append statement

I have this element:

<div class="isthisyou" id="unique_identifier"></div>

I want to use jQuery to insert a link into the div:

$('isthisyou').append('<a href="auth/create_account/'+this.id+'">Is this you?</a>');

Right now this.id is returning undefined instead of unique_identifier. What am I doing wrong?

Thanks!

Upvotes: 2

Views: 278

Answers (5)

&#193;lvaro Gonz&#225;lez
&#193;lvaro Gonz&#225;lez

Reputation: 146650

It fails for three reasons:

  1. The selector for class foo should be ".foo" rather than "foo"
  2. The ID is variable for each element; you cannot use the same value in the append() call
  3. In your code, this does not mean what you thing it means

Try this instead:

$('.isthisyou').each(function(){
    $(this).append('<a href="auth/create_account/'+this.id+'">Is this you?</a>');
});

Upvotes: 1

enduro
enduro

Reputation: 1039

There's always this

$this = $('.isthisyou');
$this.append('<a href="auth/create_account/'+$this.attr('id')+'">Is this you?</a>'); 

Upvotes: 1

Sarfraz
Sarfraz

Reputation: 382909

Try using attr instead:

$('isthisyou').append('<a href="auth/create_account/'+$(this).attr('id')+'">Is this you?</a>');

Or as shown from the comments, you can try:

$('isthisyou').append('<a href="auth/create_account/'+$('isthisyou').attr('id')+'">Is this you?</a>');

Upvotes: 0

Fabian
Fabian

Reputation: 13691

For classes in selectors use it as ".classname" (the dot), and unfortunately you have to access the id through $(this).attr().

$('.isthisyou').append('<a href="auth/create_account/'+$(this).attr("id")+'">Is this you?</a>');

If $(this).attr("id") is still undefined than that means that $(this) isn't set inside the append and you're going to have to use the following:

$('.isthisyou').each(function(){
  $(this).append('<a href="auth/create_account/'+$(this).attr("id")+'">Is this you?</a>');
});

Upvotes: 0

Bipul
Bipul

Reputation: 1367

Both of the above answers have small problems. Use

$('.isthisyou').append('<a href="auth/create_account/'+$(this).attr('id')+'">Is this you?</a>'); 

Upvotes: 0

Related Questions