Welcome to Software Development on Codidact!
Will you help us build our independent community of developers helping developers? We're small and trying to grow. We welcome questions about all aspects of software development, from design to code to QA and more. Got questions? Got answers? Got code you'd like someone to review? Please join us.
Comments on How to uncollapse an entire link tree with JavaScript?
Parent
How to uncollapse an entire link tree with JavaScript?
This data tree is comprised of clickable buttons and I want to expose all branches, in a single action, instead of clicking each vertical arrow button anew.
I have tried the following code which didn't work (it will only toggle and untoggle the first and second branches).
document.querySelectorAll(".CategoryTreeToggle").forEach((element)=>{
window.setInterval(()=>{
if (element.getAttribute('data-ct-state', 'collapsed') ) {
element.click();
}
}, 1000);
});
How to uncollapse an entire link tree with JavaScript?
Post
You can use MutationObserver
Quick example, disconnect logic is not mandatory and could be improved:
const container = document.querySelector('.CategoryTreeResult');
let disconnectTimeout;
function getCollapsedToggles() {
return container.querySelectorAll('.CategoryTreeToggle[data-ct-state=collapsed]');
}
function clickToggle(toggle) {
toggle.click();
}
const observer = new MutationObserver((mutationRecords, observer) => {
getCollapsedToggles().forEach(clickToggle);
clearTimeout(disconnectTimeout);
disconnectTimeout = setTimeout(() => {
if (getCollapsedToggles().length === 0) {
observer.disconnect();
}
}, 1000);
})
const toggles = getCollapsedToggles();
if (toggles.length > 0) {
observer.observe(container, {
childList: true,
subtree: true
});
toggles.forEach(clickToggle);
}
1 comment thread