Skip to content

Instantly share code, notes, and snippets.

@Uzwername
Created March 21, 2021 02:29
Show Gist options
  • Save Uzwername/90f48be79b6c9baf7865e612e776278e to your computer and use it in GitHub Desktop.
Save Uzwername/90f48be79b6c9baf7865e612e776278e to your computer and use it in GitHub Desktop.
const traverseHtmlElement = (rootElement, _level = 0) => {
// Get all element's children stringified if any
let rootChildren = '';
if (rootElement.childElementCount) {
rootChildren = traverseHtmlElement(rootElement.firstElementChild, _level + 1);
}
// Get all element's siblings stringified if any
let rootSiblings = '';
const nextSibling = rootElement.nextElementSibling;
if (nextSibling) {
rootSiblings = traverseHtmlElement(nextSibling, _level);
}
// The iteration part is already done above. All code
// below is just to print HTML structure in a pretty way.
const ident = ' '.repeat(_level);
const tagName = rootElement.tagName.toLowerCase();
const id = rootElement.getAttribute('id');
const classList = rootElement.classList.toString();
const rootId = id ? ` id="${id}"` : '';
const rootClasses = classList ? ` class="${classList}"` : '';
// Assemble tags with no children
if (!rootChildren) {
return ''.concat(
ident,
'<',
tagName,
rootId,
rootClasses,
' />',
'\n',
rootSiblings,
);
}
// Assemble tags with children
return ''.concat(
ident,
'<',
tagName,
rootId,
rootClasses,
'>',
'\n',
rootChildren,
ident,
`</${tagName}>`,
'\n',
rootSiblings,
);
};
const stringifiedHTML = traverseHtmlElement(document.body);
console.log(stringifiedHTML);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment