Reputation: 758
I am trying to get the EXACT html content of a div.
When using the html() function from jQuery, the result does not match the actual content.
Please check this fiddle and click on the black square:
The code:
<div id="mydiv" style="width:100px; height: 100px; background-color:#000000; cursor:pointer;">
<div id="INSIDE" style="background-color:#ffffff; border-style:none;"></div>
</div>
$('#mydiv').click(function() {
alert($(this).html());
});
jQuery change the color to RGB format and remove the border-style attribute.
How can I solve this problem?
Upvotes: 0
Views: 176
Reputation: 10675
What you want to do is unfortunately not possible. The original HTML is not available after it is parsed by the browser, so you have to jump through some hoops to prevent the browser from processing it.
One possible solution that I've used before is to wrap the HTML in comment tags, which would remain unchanged by the browser. You can then extract the comment using jQuery's .text()
method; strip out the comment tags with string replacement; make the necessary changes to the markup; and then inject it back into the document.
The other alternative is to use AJAX to load the HTML. Make sure you set the contentType
to 'text'
so it doesn't get processed by the browser.
Upvotes: 1
Reputation: 943564
The browser consumes the HTML, generates a DOM, then discards the HTML. innerHTML
(which is what .html()
eventually hits) gives a serialisation of the DOM back to HTML.
If you want to get the raw HTML, then you'll need to use XMLHttpRequest
to fetch the source code of the current URL and then process it yourself.
Upvotes: 9