Expand and Collapse of 4 level hierarchical rows in html table

I have some hierarchical data in a table structure as so: (example 1)

A

A.1

A.1.1 

A.1.2

   A.1.2.3

A.2

A.2.1

A.2.2

  A.2.2.3

I would like to be able to expand and collapse within each level, so example, If I click on A.2, it’s children should collapse: (example 2)

A

A.1

A.1.1 

A.1.2 

   A.1.2.3

A.2

B

B.1

B.1.1

B.1.2

B.2

B.2.1

B.2.2

And if I click A, all of its children should collapse: (example 3)

A

B

B.1

B.1.1

B.1.2

B.2

B.2.1

B.2.2

and if I expand A again, A.2 should still remain collapsed (children hidden) (example 4)

A

A.1

A.1.1 

A.1.2 

A.2

B

B.1

B.1.1

B.1.2

B.2

B.2.1

B.2.2

I have tried this code:

toggleElement = function(context) {
      let current = context.parentElement
      if (current.className == 'level1') {
        toggleLevel1(current)
      } else if (current.className == 'level2') {
        toggleLevel2(current)
      }
    };

    toggleLevel1 = function(current) {
      let nextSibling = current.nextElementSibling;

      while (nextSibling && nextSibling.className == 'level2') {
        nextSibling.hidden = nextSibling.hidden ? false : true
        nextSibling = nextSibling.nextElementSibling
        while (nextSibling && nextSibling.className == 'level3') {
          if (!nextSibling.hidden) {
            nextSibling.hidden = nextSibling.hidden ? false : true
          }
          nextSibling = nextSibling.nextElementSibling
        }
      }
    };

    toggleLevel2 = function(current) {
      let nextSibling = current.nextElementSibling;

      while (nextSibling && nextSibling.className == 'level3') {
        nextSibling.hidden = nextSibling.hidden ? false : true
        nextSibling = nextSibling.nextElementSibling
      }
    };
B.2.2

the problem is that it is limited to 3 level of data and i have 4 levels.

Can anyone help?

Thanks in advance.