SerGit
SerGit

Reputation: 3

getElementByTagName iteration unexpected result

I'm building this webpage where I want some subheadings to dropdown their hidden content when clicked on.... I did manage to make them all working triggers but they don't work exactly as intended. Since each subheading and its content is contained within a SECTION tag, I decided to gather all elements with that tag by using "getElementsByTagName" in the JS file and iterate through each of them with a FOR loop, like this:

let section;

for (let i=0; i<document.getElementsByTagName('section').length; i++)
    {
        section=document.getElementsByTagName('section')[i];//This makes the "SECTION" variable become each one of the sections (which contain a subheading and a paragraph each)

        section.children[0].onclick= function()
            {//The first child element of each SECTION is the subheading, the second one is the paragraph
                if(section.children[1].style.display==='inline-block')
                    {
                        section.children[1].style.display='none';
                    }
                else
                    {
                        section.children[1].style.display='inline-block';
                    }
            }
    }

Now, the problem is that for some reason, while I can see that the "for" loop must be working since the "onclik" event is indeed taking each of the subheadings as a trigger element... I can't understand why clicking on any of the subheadings, always drops down only the content on the last SECTION, it doesn't make sense to me, help please!!

You can view all the files for the webpage here: https://github.com/SerGit-MondraHub/my-web/tree/public

And you can see it in action here: https://sergit-mondrahub.github.io/my-web/

Upvotes: 0

Views: 27

Answers (0)

Related Questions