1. function validateHTML(html) {
  2. try {
  3. // Create a DOMParser to parse the HTML string
  4. const parser = new DOMParser();
  5. const doc = parser.parseFromString(html, 'text/html');
  6. // Check for required elements and attributes with default values
  7. if (!doc.querySelector('html')) {
  8. console.error('Error: Missing <html> element.');
  9. return { errors: ['Missing <html> element'] };
  10. }
  11. const htmlElement = doc.querySelector('html');
  12. if (!htmlElement.lang) {
  13. htmlElement.lang = 'en'; // Set default language
  14. }
  15. if (!doc.querySelector('head')) {
  16. console.warn('Warning: Missing <head> element. Defaulting to empty <head>.');
  17. }
  18. const headElement = doc.querySelector('head');
  19. if (!headElement.title) {
  20. headElement.title = 'Default Title'; // Set default title
  21. }
  22. if (!doc.querySelector('body')) {
  23. console.error('Error: Missing <body> element.');
  24. return { errors: ['Missing <body> element'] };
  25. }
  26. const bodyElement = doc.querySelector('body');
  27. if (!bodyElement.style) {
  28. bodyElement.style = {}; // Ensure style attribute exists
  29. }
  30. if (!bodyElement.style.fontFamily) {
  31. bodyElement.style.fontFamily = 'sans-serif'; // Set default font-family
  32. }
  33. if (!bodyElement.style.margin) {
  34. bodyElement.style.margin = '0'; // Set default margin
  35. }
  36. // Check for common missing elements (expand as needed)
  37. if (!doc.querySelector('title')) {
  38. console.warn('Warning: Missing <title> element. Defaulting to empty <title>.');
  39. }
  40. const titleElement = doc.querySelector('title');
  41. if (!titleElement) {
  42. titleElement = doc.createElement('title');
  43. headElement.appendChild(titleElement);
  44. titleElement.textContent = 'Default Title';
  45. }
  46. return { errors: [] }; // No errors found
  47. } catch (e) {
  48. console.error('Error parsing HTML:', e);
  49. return { errors: ['HTML parsing error'] };
  50. }
  51. }
  52. // Example Usage (replace with your HTML string)
  53. // const htmlString = '<html lang=""><body><div>Hello</div></body></html>';
  54. // const validationResult = validateHTML(htmlString);
  55. // if (validationResult.errors.length > 0) {
  56. // console.error('Validation Errors:', validationResult.errors);
  57. // } else {
  58. // console.log('HTML is valid (with default values)');
  59. // }

Add your comment