function validateHTML(html) {
try {
// Create a DOMParser to parse the HTML string
const parser = new DOMParser();
const doc = parser.parseFromString(html, 'text/html');
// Check for required elements and attributes with default values
if (!doc.querySelector('html')) {
console.error('Error: Missing <html> element.');
return { errors: ['Missing <html> element'] };
}
const htmlElement = doc.querySelector('html');
if (!htmlElement.lang) {
htmlElement.lang = 'en'; // Set default language
}
if (!doc.querySelector('head')) {
console.warn('Warning: Missing <head> element. Defaulting to empty <head>.');
}
const headElement = doc.querySelector('head');
if (!headElement.title) {
headElement.title = 'Default Title'; // Set default title
}
if (!doc.querySelector('body')) {
console.error('Error: Missing <body> element.');
return { errors: ['Missing <body> element'] };
}
const bodyElement = doc.querySelector('body');
if (!bodyElement.style) {
bodyElement.style = {}; // Ensure style attribute exists
}
if (!bodyElement.style.fontFamily) {
bodyElement.style.fontFamily = 'sans-serif'; // Set default font-family
}
if (!bodyElement.style.margin) {
bodyElement.style.margin = '0'; // Set default margin
}
// Check for common missing elements (expand as needed)
if (!doc.querySelector('title')) {
console.warn('Warning: Missing <title> element. Defaulting to empty <title>.');
}
const titleElement = doc.querySelector('title');
if (!titleElement) {
titleElement = doc.createElement('title');
headElement.appendChild(titleElement);
titleElement.textContent = 'Default Title';
}
return { errors: [] }; // No errors found
} catch (e) {
console.error('Error parsing HTML:', e);
return { errors: ['HTML parsing error'] };
}
}
// Example Usage (replace with your HTML string)
// const htmlString = '<html lang=""><body><div>Hello</div></body></html>';
// const validationResult = validateHTML(htmlString);
// if (validationResult.errors.length > 0) {
// console.error('Validation Errors:', validationResult.errors);
// } else {
// console.log('HTML is valid (with default values)');
// }
Add your comment