Lunster
Lunster

Reputation: 906

Is there a way to validate the HTML of a page after AJAX operations are performed on it?

I'm writing a web app that inserts and modifies HTML elements via AJAX using JQuery. It works very nicely, but I want to be sure everything is ok under the bonnet. When I inspect the source of the page in IE or Chrome it shows me the original document markup, not what has changed since my AJAX calls.

I love using the WC3 validator to check my markup as it occasionally reminds me that I've forgotten to close a tag etc. How can I use this to check the markup of my page after the original source served from the server has been changed via Javascript?

Thank you.

Upvotes: 2

Views: 218

Answers (3)

Naeem Sarfraz
Naeem Sarfraz

Reputation: 7430

Both previous answers make good points about the fact the browser will 'fix' some of the html you insert into the DOM.

Back to your question, you could add the following to a bookmark in your browser. It will write out the contents of the DOM to a new window, copy and paste it into a validator.

javascript:window.open("").document.open("text/plain", "").write(document.documentElement.outerHTML);

Upvotes: 2

ssokolow
ssokolow

Reputation: 15355

If you're just concerned about well-formedness (missing closing tags and such), you probably just want to check the structure of the chunks AJAX is inserting. (Once it's part of the DOM, it's going to be well-formed... just not necessarily the structure you intended.) The simplest way to do that would probably be to attempt to parse it using an XML library. (one with an HTML mode that can be made strict, if you're not using XHTML)

Actual validation (Testing the "You can't put tag X inside tag Y" rules which browsers generally don't care too much about) is a lot trickier and, depending on how much effort you're willing to put into it, may not be worth the trouble. (Because, if you validate them in isolation, you'll get a lot of "This is just a fragment" false positives)

Whichever you decide to use, you need to grab the AJAX responses before the browser parses them if you want a reliable test result. (While they're still just a string of text rather than a DOM tree)

Upvotes: 1

Loïc Février
Loïc Février

Reputation: 7750

Use developer tool in chrome to explore the DOM : it will show you all the HTML you've added in javascript.

You can now copy it and paste it in any validator you want.

Or instead of inserting code in JQuery, give it to the console, the browser will then not be able to close tags for you.

console.log(myHTML)

Upvotes: 2

Related Questions