Checking dynamic HTML generated by JavaScript

How can I verify that the content generated by JavaScript is valid HTML? For example, the following document will undergo static HTML validation (for example, validator.nu), will not cause JavaScript errors, and will be displayed without complaint in the browser:

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>test</title> <script> window.onload = function() { var text = document.createTextNode('nested anchor'); var anchor = document.createElement('a'); var nested_anchor = document.createElement('a'); nested_anchor.appendChild(text); anchor.appendChild(nested_anchor); document.getElementsByTagName('body')[0].appendChild(anchor); }; </script> </head> <body> <p>test</p> </body> </html> 

However, the output contains an anchor inside another anchor element, which is invalid according to the HTML5 specification. Is there any way to check for these errors?

+4
source share
4 answers

You can output the resulting HTML as a String, paste it into a valid document, and send it for verification. In your case, using jQuery var htmlText = $(anchor).html() .

Or even simpler, output all the resulting html console.log($("html").html())

+2
source

You can use the Validate Local HTML function on the web page of the developer toolbar (Chrome and Firefox). This function will use the W3 validator to validate the generated HTML.

Instead of downloading the extension, you can also use my JavaScript shortcut to check local HTML. Bookmark and paste the code below in the "URL" field. Then, when you want to check the local HTML, click on the bookmarklet.
The code below is standalone and does not require any frameworks.

 javascript:void(function(){ var form = document.createElement("form"); form.method = "POST"; form.enctype = "multipart/form-data"; form.action = "http://validator.w3.org/check"; form.target = "_blank"; /* Get local HTML*/ var html = "<html>" + document.documentElement.innerHTML + "</html>"; var post_data = { fragment: html,/*Settings for validator*/ prefill: "0", doctype: "HTML5", prefill_doctype: "html401", group: "0", ss: "1", outline: "1" }; for(var name in post_data){ (function(){ var t = document.createElement("textarea"); t.name = name; t.value = post_data[name]; form.appendChild(t) })() } document.body.appendChild(form); form.submit(); /* Open validator, in new tab*/ document.body.removeChild(form); })() 
+2
source

Just save the html source after it is fully downloaded and use this static file for verification.

0
source

"Just save the html source after it is fully downloaded and use this static file to verify."

I would suggest that if it worked, the browser would fix many problems when it takes a snapshot of the HTML from the DOM.

0
source

All Articles