I have a div with 5 elements, and I only want to show 1 at a time.
Is there a way to change .classname:nth-child(1)
to .classname:nth-child(3)
in javascript?
Or do I need a different approach?
I have a display none on the parent and i want to display flex the nth child
2
Answers
I suppose this different approach may be viable. The snippet uses event delegation:
In reply to @tacoshys
I beg to differ. Let’s cite Donald Knuth here
About inefficiency of event delegation I cite the linked page @javascript.info:
Sure, it’s up to anyone to make it more scalable. The snippet was just an rough indication for how to solve OPs problem.
Readability, like beauty, is in the eye of the beholder.
Now about your code: the
const
you define for thediv.className
nodeList may give you trouble later on, e.g. when elements are added dynamically. So, about scalability …The latter is demonstrated in the next snippet (which uses your idea – which, by the way, is not a bad idea ;).
@Kooilnc Answer works but has 2 major issues:
Inefficient
For once the code appends the
EventListener
to the whole document and then checks on every click if the button was clicked. The `EventListener should be added to the button itself:Then he uses
querySelectorAll
which returns a NodeList. Then he iterates through the NodeList and checks every Element if it has the "active" class. If he has found that element in his iteration he removes that class. The efficient (fast and resource-saving) solution is to select the element that has the class directly and remove the class from that element:No need for an iteration that takes more time and resources.
Scalability
Scalability should always be a concern. The code from the mentioned answer has the issue that it requires to be exact 5 elements. It will no longer work correctly if you have more or fewer elements. As such it requires manual maintenance and fixing as soon as you add or removes content.
A good and clean code should not care about how many elements you have to work correctly. The trick here is to check in the script how many elements you have by using
NodeList.length
.Improved Solution
How does the code Work?
the
NodeList
+ 1
to the index to select the next element in the NodeList unless the index is equal to the length of the NodeList in which case it resets the index to0