xylar
xylar

Reputation: 7673

Find id element inside JSON html content using jQuery

I am returning JSON inside an ajax request which has html as one of its values.

html:
"<div id="foo">
    <p>FOO</p>
</div>

<div id="bar">
    <p>BAR</p>
</div>"

I would like to add #foo to one element and #bar to another. I have tried the following:

$('#add-foo-html-here').html($(response.html).find('#foo'));

but this fails to find #foo. What is the best way to do this? Should I be adding the html content to a temp element and then finding the id?

Upvotes: 0

Views: 1067

Answers (2)

pktangyue
pktangyue

Reputation: 8524

Use .filter() instead of .find().

$('#add-foo-html-here').html($(response.html).filter('#foo'));

.find() only find the children elements. But here #foo is not a child.

Upvotes: 2

adeneo
adeneo

Reputation: 318252

You'll need a parent to use find() ???

var div = $('<div />');
    div.html(response.html);

$('#elementID').html( div.find('#foo') );

Upvotes: 1

Related Questions