Reputation: 2498
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
Reputation: 146650
It fails for three reasons:
foo
should be ".foo"
rather than "foo"
this
does not mean what you thing it meansTry this instead:
$('.isthisyou').each(function(){
$(this).append('<a href="auth/create_account/'+this.id+'">Is this you?</a>');
});
Upvotes: 1
Reputation: 1039
There's always this
$this = $('.isthisyou');
$this.append('<a href="auth/create_account/'+$this.attr('id')+'">Is this you?</a>');
Upvotes: 1
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
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
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