0

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?

2
  • I'm guessing the element you are inserting to actually has the ID #this (does seem strange)? If the HTML is valid (there are some quoting issues above), it should work! Also, if they don't have a parent, you can't find() them, you'd need to append to them to an empty parent first. Commented Feb 26, 2013 at 10:49
  • Sorry that was just an example. I'll update it for clarification. Commented Feb 26, 2013 at 10:51

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

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

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

1 Comment

Thanks for the clarification with the find(). This is what I was going to do when creating the temp element.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.