0

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:

http://jsfiddle.net/qRska/6/

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?

4

2 Answers 2

9

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.

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

Comments

1

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.

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.