0

I'm trying to wrap a jQuery object in a list. The object is

<a class="medium button" title="Title"">Sample</a> 

and the interaction

$(".medium").click(function() {
  $(".list4").append("<li>");
  $(".list4").append($(this));
  $(".list4").append("</li>");
});

but this inevitably ends up in a blank list item. But if I do something like

$(".medium").click(function() {
  $(".list4").append("<li>");
  $(".list4").append($(this).html());
  $(".list4").append("</li>");
});

the item doesn't have the link. What should I do?

Rio
  • 14,182
  • 21
  • 67
  • 107

3 Answers3

3

Here is another way:

$(".medium").click(function() {
  $("<li />").append(this).appendTo('.list4');
});

or if you want to leave the element at it's original place, you can clone it:

$("<li />").append($(this).clone()).appendTo('.list4');

As @Marc B already explained in his answer, every append inserts a new DOM node, not just HTML text. When you call $element.append('<div>'), then the browser (or even jQuery) will correct the "broken" HTML.

Community
  • 1
  • 1
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
0

try

$('.list4').append('<li>' + $(this).html() + '</li>');

each append operation generates at least one new node. Calling it 3 times like that generates 3 new nodes. So... embed a full HTML snippet to be appended, which'll generate just one new <li>

Marc B
  • 356,200
  • 43
  • 426
  • 500
  • +1 - OP, you're effectively inserting three nodes into the list, not raw HTML. – Tejs Aug 25 '11 at 17:09
  • This answer inspired me to create a div for each `.medium` object, like `` and using `$('.list4').append('
  • ' + $(this).parent().html() + '
  • ');` – Rio Aug 25 '11 at 17:11
  • @Marc B - `$(this).html()` will only return "Sample". You'll lose the hyperlink this way. – 65Fbef05 Aug 25 '11 at 19:10
  • @65FBef05. true enough. easy to work around, though: http://stackoverflow.com/questions/2419749/get-selected-elements-outer-html – Marc B Aug 25 '11 at 19:18
  • @Marc B - Thanks for the link. After reading through the answers, I was inspired to turn my answer below into a plugin. :) – 65Fbef05 Aug 25 '11 at 19:43