Skip to content Skip to sidebar Skip to footer

JQuery HTML Parser Is Removing Some Tags Without A Warning, Why And How To Prevent It?

Here is the thing, I have a textarea (with ID 'input_container') full of HTML code, the simple example is: <

Solution 1:

From the jQuery documentation:

When passing in complex HTML, some browsers may not generate a DOM that exactly replicates the HTML source provided. As mentioned, we use the browser's .innerHTML property to parse the passed HTML and insert it into the current document. During this process, some browsers filter out certain elements such as <html>, <title>, or <head> elements. As a result, the elements inserted may not be representative of the original string passed.

This should work instead:

$('<html />').append($('<head />')).append($('<body />').append($('<a href="www.example.com">the other place</a>')));

This is kind of a weird thing to do, though- you might want to think about other ways to do what you're trying to accomplish, I worry that you might be suffering from the XY Problem.


Solution 2:

I suspect that you're using jQuery load or an AJAX call.

This will attempt to load the document into your current DOM. It will get the contents of the HEAD and BODY tags via innerHtml, but not the tags themselves (including the HTML tag, naturally).

From the jQuery Load documentation

jQuery uses the browser's .innerHTML property to parse the retrieved document and insert it into the current document. During this process, browsers often filter elements from the document such as <html>, <title>, or <head> elements. As a result, the elements retrieved by .load() may not be exactly the same as if the document were retrieved directly by the browser.

EDIT: If you are trying to get the full HTML for your page, the same thing applies. It's going to use the browser's innerHtml function which will behave as described above. HTML doesn't really exist once the DOM is loaded, so going the opposite direction won't necessarily be 100% correct.

When you load that HTML into the DOM, it'll ignore the tags as they don't actually get loaded at all. Then when you're retrieving, all that's left is the link (as well as whatever you have in the HEAD, but you don't have anything in there...).


Post a Comment for "JQuery HTML Parser Is Removing Some Tags Without A Warning, Why And How To Prevent It?"