Format HTML with indentation for improved readability and debugging.
Code
Utilitiesconst format = (node, level) => {
const ind = ' '.repeat(indent);
let result = '';
for (const child of node.childNodes) {
const pad = ind.repeat(level);
if (child.nodeType === 3) {
const text = child.textContent.trim();
if (text) result += pad + text + '\n';
} else if (child.nodeType === 1) {
const tag = child.tagName.toLowerCase();
const attrs = [...child.attributes].map(a => ` ${a.name}="${a.value}"`).join('');
if (child.childNodes.length === 0) {
result += pad + `<${tag}${attrs}></${tag}>\n`;
} else {
result += pad + `<${tag}${attrs}>\n` + format(child, level + 1) + pad + `</${tag}>\n`;
}
}
}
return result;
};
const doc = new DOMParser().parseFromString(html, 'text/html');
const isFullDoc = /<html[\s>]/i.test(html);
const root = isFullDoc ? doc.documentElement : doc.body;
return format(root, 0).trim();Parameters
HTML string to format.
Number of spaces for indentation.
Browser·fetch() may be limited by CORS
More JavaScript Snippets
Add Days to Date
Add a specified number of days to a date and return the result in ISO format.
Add Query Parameter
Add or update a query parameter in a URL string.
Array Difference
Find elements in the first array that are not present in the second array.
Array Frequencies
Count how many times each value appears in an array and return a frequency map.
Array Head
Get the first n elements of an array.
Array Intersection
Find common elements that exist in both arrays.