jQuery - find a element inside a another element and getting it's html content
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开发者_JS百科 the element's contents only. I want to get the element tags too.
How can I do that?
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.
精彩评论