1

so a Ajax call will return some data as html.

I'm creating a element from this data with var comment = $("<ul />").html(data);

Now I want to get the html content from another element inside the comment element I just created above. I'm using var commentbody = comment.find(".comment-body").html();

This works, but the problem is that I get the element's contents only. I want to get the element tags too.

How can I do that?

2
  • Out of curiosity, why do you need its HTML string?
    – user113716
    Jan 20, 2011 at 1:21
  • @patrick dw: because I want to separate the code from the comment template. If I would get only the comment content text I would have to hardcode my own comment template in the javascript (or a part of it). Initially I wanted to replace the entire list item, but comments can have child comments so that would not work :)
    – Alex
    Jan 20, 2011 at 1:24

1 Answer 1

2

You can do this:

var commentbody = comment.find(".comment-body");

var outerHTML = commentbody[0].outerHTML || 
                          commentbody.clone().appendTo('<div>').parent().html();

Here you first find the .comment-body element you want. Then you access the DOM element with [0] and get its outerHTML property.

If it doesn't have an outerHTML property, then make a clone()(docs) of it, appendTo()(docs) a new <div>, traverse up to the parent()(docs) <div> and get its html()(docs) content.

This answer assumes there's only one .comment-body to be found.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.