views:

64

answers:

5

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!

A: 

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>');
});
Fabian
Returns an error that attr is not defined. I think we might need a $ in there somewhere.
Summer
+1 You're right, fixed.
Fabian
A: 

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>');
Sarfraz
This looks promising, but unfortunately $(this).attr('id') is still returning undefined when I try it out...
Summer
its `$('.isthisyou') ...`
j.
Yes. I ended up using $('.isthisyou').attr('id') internally and it worked. Wish there were a prettier way.
Summer
A: 

Both of the above answers have small problems. Use

$('.isthisyou').append('<a href="auth/create_account/'+$(this).attr('id')+'">Is this you?</a>'); 
Bipul
This creates a link auth/create_account/undefined. Is $(this) referring to the literal string to be appended, instead of its parent?
Summer
A: 

There's always this

$this = $('.isthisyou');
$this.append('<a href="auth/create_account/'+$this.attr('id')+'">Is this you?</a>'); 
enduro
Thanks, it worked! I changed $this to $myvar -- just so I wouldn't confuse myself by using the 'this' syntax in a variable I defined myself.
Summer
This code doesn't work properly with two or more items. If you only have one item, you could just hardcode the ID as well.
Álvaro G. Vicario
+1  A: 

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>');
});
Álvaro G. Vicario