Skip to content

Instantly share code, notes, and snippets.

@yitonghe00
Created May 17, 2022 06:18
Show Gist options
  • Save yitonghe00/f12a47769d36b27d1f94fc51b43ed6b3 to your computer and use it in GitHub Desktop.
Save yitonghe00/f12a47769d36b27d1f94fc51b43ed6b3 to your computer and use it in GitHub Desktop.
<tab-panel>
<div data-tabname="one">Tab one</div>
<div data-tabname="two">Tab two</div>
<div data-tabname="three">Tab three</div>
</tab-panel>
<script>
function asTabs(node) {
const tabList = document.createElement('div');
const tabs = Array.from(node.children).map((child) => {
const button = document.createElement('button');
button.textContent = child.getAttribute('data-tabname');
const tab = { node: child, button };
button.addEventListener('click', () => selectTab(tab));
tabList.appendChild(button);
return tab;
});
node.insertBefore(tabList, node.firstChild);
const selectTab = (selectedTab) => {
tabs.forEach((tab) => {
const selected = selectedTab === tab;
tab.node.style.display = selected ? '' : 'none';
tab.button.style.backgroundColor = selected ? 'yellow' : '';
});
};
selectTab(tabs[0]);
}
asTabs(document.querySelector("tab-panel"));
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment