Alex Rivera | Logout

Does jQuery strip some html elements from a string when using .html()?

Asked 2010-03-21T21:41:13.270
18

I have a var that contains a full html page, including the head, html, body, etc. When I pass that string into the .html() function, jQuery strips out all those elements, such as body, html, head, etc, which I don't want.

My data var contains:

<html>
<head>
<title>Untitled Document</title>
</head>
<body>
</body>
</html>

Then my jQuery is:

// data is a full html document string
data = $('<div/>').html(data);
// jQuery stips my document string!
alert(data.find('head').html());

I am needing to manipulate a full html page string, so that I can return what is in the element. I would like to do this with jQuery, but it seems all of the methods, append(), prepend() and html() all try to convert the string to dom elements, which remove all the other parts of a full html page.

Is there another way that I could do this? I would be fine using another method. My final goal is to find certain elements inside my string, so I figured jQuery would be best, since I am so used to it. But, if it is going to trim and remove parts of my string, I am going to have to look for another method.

Ideas?

Edit
Report

1 Answer

0

There is no need for the container div.

Have you tried this?:

var foo = $(data);  // data is your full html document string

Then you can search inside of it like so:

$('.someClass', foo); // foo is the document you created earlier

Update:

As another answered mentioned, how this will act comes down to the browser.

I looked at the jQuery docs a bit and found this:

When the HTML is more complex than a single tag without attributes, as it is in the above example, the actual creation of the elements is handled by the browser's innerHTML mechanism. Specifically, jQuery creates a new <div> element and sets the innerHTML property of the element to the HTML snippet that was passed in.

So it seems that when you are using a whole html doc as a string, it's no different than setting the innerHTML property of a div you make using createElement.

answered 2010-03-21T21:45:16.543

Your Answer