3

I'm trying to create some dynamic html through jquery, filter it to the part I'm interested in, and append that section of html to an existing element on the page but its not working. What am I doing wrong in this fiddle?

http://jsfiddle.net/3zKeL/4/

HTML:

<div id="output">This is the output:<br></div>

jQ:

var response = "<html><body><h1>hello</h1></body></html>";
$(response).filter("body").appendTo("#output");
1
  • If you do console.log($(response)), you will see just [ <h1>​hello​</h1>​], So you can use $(response).appendTo("#output");​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​ Commented Jun 2, 2012 at 18:48

2 Answers 2

3
$(response)
          .filter(function() { 
             return $("body");
          })
          .appendTo("#output");

DEMO

You can do also

$('<div/>')           // add response to fake div
    .append(response)  
    .find('body')     // find your target
    .appendTo('#output'); // append the target

DEMO

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

1 Comment

I was too quick on accepting. The filter is returning everything (title and style elements from head tag) not just the contents of the body tag: jsfiddle.net/dcwNJ
0

Ok, figured this out. jQuery vomits silently when it encounters the "html" and "body" tags in dynamically generated html. I simply had to replace or strip those tags out and now it works as expected.

http://jsfiddle.net/pqyeM/13/

var response = "<html><head><title>test</title><style>body{font-size:.9em;}</style></head><body bgcolor=\"white\"><h1>hello</h1></body></html>";

// we have to remove/replace certain tags or jquery will vomit with unexpected results
var modifiedResponse = response.replace("<html>", "").replace("</html>", "").replace("<body", "<div id='content'").replace("</body>", "</div>");

var wrappedSet = $(modifiedResponse);

wrappedSet.filter("div[id='content']").appendTo("#output");

Comments

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.