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.
How to uncollapse the first and second tiers of a link tree in JavaScript?
I wish to display the first and second branches of a link tree with JavaScript.
I want to show these branches in a single action, instead of clicking each vertical arrow (link) anew.
As can be read in the linked webpage, one can click the vertical arrow to get the next branch (if there is one).
Code which I have tried and failed
document.querySelectorAll(".CategoryTreeToggle").forEach( (element)=>{
if (element.hasAttribute('data-ct-state', 'collapsed') ) {
element.click();
}
});
For some reason, with the following code, all branches, whether collapsed or manually expanded, will collapse.
How to uncollapse the first and second branches of a link tree in JavaScript?
2 answers
The following users marked this post as Works for me:
User | Comment | Date |
---|---|---|
user56529 | (no comment) | Apr 10, 2022 at 10:20 |
The first item your selector returns is the top level arrow. hasAttribute
just tells us if the attribute is present, not what the value is. So basically your condition is returning true for all elements. Since that includes the top level element, it gets clicked and everything collapses.
Try:
document.querySelectorAll(".CategoryTreeToggle").forEach( (element)=>{
if (element.getAttribute('data-ct-state') === 'collapsed' ) {
element.click();
}
});
1 comment thread
According to the documentation, the hasAttribute
method expects only one argument (the attribute's name), and it tells only if that attribute is present, regardless of its value. Hence, the return is a boolean (only true
or false
).
When you pass more than one argument, only the first one is considered, and all the others are ignored.
In your case, all the elements have the data-ct-state
attribute, therefore hasAttribute
always returns true
.
If you want to check an attribute's value, you can do like the other answer said (use getAttribute
and check its value), but in this case you could also search for elements that have a specific value for the attribute, using an attribute selector:
document.querySelectorAll('.CategoryTreeToggle[data-ct-state="collapsed"]').forEach(e => e.click());
In the code above, querySelectorAll
will search only for the elements that has the CategoryTreeToggle
class and the data-ct-state
attribute has the value equals to collapsed
. With that, there's no need to use an if
clause, because now we're sure that all the elements are the ones that I need to click.
1 comment thread