Search code examples
javascriptfunctiontypeerrorthis

Uncaught TypeError: Cannot read properties of undefined (reading 'className') at HTMLDivElement.<anonymous>


Click here to see the image I am new to javascript. I am trying to switch between the sections and I am getting a TypeError. Don't know what to do.

const sections = document.querySelectorAll('.section');
const sectBtns  = document.querySelectorAll('.controls');  
const sectBtn = document.querySelectorAll('.control');     
const allSections = document.querySelector('.main-content');  


function PageTransition() {
    //Button click active class
    for(let i = 0; i < sectBtn.length; i++) {
        sectBtn[i].addEventListener('click', function(){
            let currentBtn = document.querySelectorAll('.active-btn');
           
            currentBtn[0].className = 
            currentBtn[0].className.replace('active-btn', '');

            this.className += 'active-btn';
        })
    }
}

And here's my HTML code. I have element with the class name active-btn.

<body class="main-content">
    <header class="section sec1 header active">

    </header>    

    <main>
        <section class="section sec2 about"></section>
        <section class="section sec3 portfolio"></section>
        <section class="section sec4 skills"></section>
        <section class="section sec5 contact"></section>
    </main>
    
    <div class="contorls">
        <div class="control control-1 active-btn">
            <i class="fas fa-home"></i>
        </div>
        <div class="control control-2" data-id="about">
            <i class="fas fa-user"></i>
        </div>
        <div class="control control-3" data-id="portfolio">
            <i class="fas fa-briefcase"></i>
        </div>
        <div class="control control-4" data-id="skills">
            <i class="fas fa-newspaper"></i>
        </div>
        <div class="control control-5" data-id="contact">
            <i class="fas fa-envelope-open"></i>
        </div>
           
    </div>

<script src="app.js"></script>
</body>

Solution

  •         currentBtn[0].className = 
            currentBtn[0].className.replace('active-btn', '');
    
            this.className += 'active-btn';
    

    I was having the same problem. Here, when you are changing the classname. Instead of this.className += "active-btn" it should be this.className += " active-btn" with a space at the beginning of the class name "active-btn". If no space will be used the class name will be concatenated to the other class name.