Zak Henry
Zak Henry

Reputation: 2185

jQuery: how to I append $(this)

I have a jQuery method that I want to append the element $(this) to.

My code is

$("#actions ul" ).append($(this)); 

However this does seem to do anything. Using the line

.append($(this).html()) 

does work, but it only grabs the child of $(this) (a div) not the whole element (an li).

I'm probably doing something moronic, hopefully someone can point this out to me.

Upvotes: 8

Views: 23842

Answers (4)

Jon
Jon

Reputation: 151

Actually you want to use appendTo, this will grab the entire element.

$(this).appendTo("#actions ul");

Upvotes: 0

David Tang
David Tang

Reputation: 93684

Without knowing exactly what this refers to, the only reason I can think of for $(this).html() to work and not $(this) is that the former method creates a new element from the html code whereas appending $(this) will move the element.

See if the below fixes your problem:

$("#actions ul" ).append($(this).clone()); 

Upvotes: 9

Rob Sobers
Rob Sobers

Reputation: 21135

It sounds like this is set to a selector that finds the <div> instead of the <li>. You can either change the selector or, like miket2e suggests, use .parent() instead. Note: you should not have to use .html() as well since the .append function can take a HTML string or a jQuery object.

If you post the value of this, we could provide a more concrete answer.

Upvotes: 0

Michael Low
Michael Low

Reputation: 24506

It's not that clear what $(this) refers to, but if it's the child element of the element you want then $(this).parent() should get the parent element you're after.

Upvotes: 0

Related Questions