Cannot read property 'addEventListener' of null while trying to make tabs work











up vote
-1
down vote

favorite












So for some reason, it returns as Cannot read property 'addEventListener' of null in my console. Trying to make the tabs work. Can't find what is wrong with the code. Any help would be appreciated. Or if you could give me a better way of how to make tabs with JS.



This is my Javascript code






function onTabClick(event) {
let activeTabs = document.querySelectorAll(".active");



activeTabs.forEach(function(tab) {
tab.className = tab.className.replace("active", "");
});

// activate new tab and panel
event.target.parentElement.className += " active";
document.getElementById(event.target.href.split("#")[1]).className +=
" active";
}

var element = document.getElementById("nav-tab");
element.addEventListener("click", onTabClick, false);

And this is my HTML

<div class="container">
<!-- Tab panes -->
<div class="tab-content">
<div class="tab-pane active" id="home">
<h4>Home Panel Content</h4>
<p>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Quidem
iure quos cum, saepe reprehenderit minima quasi architecto numquam
nesciunt dicta. Qui excepturi recusandae vitae maiores, inventore
sequi? Rerum, odio omnis.
</p>
</div>
<div class="tab-pane" id="profile">
<h4>Profile Panel</h4>
<p>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Quidem
iure quos cum, saepe reprehenderit minima quasi architecto numquam
nesciunt dicta. Qui excepturi recusandae vitae maiores, inventore
sequi? Rerum, odio omnis. Lorem ipsum dolor sit amet consectetur
adipisicing elit. Alias distinctio, tempora incidunt aliquid
adipisci, minus rerum optio libero quae provident sed at
dignissimos, quia nostrum! Fuga dolorum quia hic magni.
</p>
</div>
<div class="tab-pane" id="messages">
<h4>Messages Panel</h4>
<p>
Lorem ipsum dolor sit amet consectetur, adipisicing elit. Fugiat
quos, at qui aspernatur minus animi hic sunt necessitatibus
incidunt molestiae reprehenderit ratione neque odit ipsa. Nemo
laborum consequatur adipisci beatae!
</p>
</div>
<div class="tab-pane" id="settings">
<h4>Settings Panel</h4>
<p>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Minima
possimus sed odit iste vitae, magnam amet illum laudantium ea!
Fugiat consectetur consequuntur qui eos obcaecati sequi ipsam
repellat vero voluptate.
</p>
</div>
</div>
<!-- Tabs -->
<ul id="nav-tab" class="nav">
<li class="active"><a href="#home">Home</a></li>
<li><a href="#profile">Profile</a></li>
<li><a href="#messages">Messages</a></li>
<li><a href="#settings">Settings</a></li>
</ul>
</div>












share|improve this question






















  • Works perfectly fine. Press "Run code snippet".
    – CertainPerformance
    Nov 11 at 4:01















up vote
-1
down vote

favorite












So for some reason, it returns as Cannot read property 'addEventListener' of null in my console. Trying to make the tabs work. Can't find what is wrong with the code. Any help would be appreciated. Or if you could give me a better way of how to make tabs with JS.



This is my Javascript code






function onTabClick(event) {
let activeTabs = document.querySelectorAll(".active");



activeTabs.forEach(function(tab) {
tab.className = tab.className.replace("active", "");
});

// activate new tab and panel
event.target.parentElement.className += " active";
document.getElementById(event.target.href.split("#")[1]).className +=
" active";
}

var element = document.getElementById("nav-tab");
element.addEventListener("click", onTabClick, false);

And this is my HTML

<div class="container">
<!-- Tab panes -->
<div class="tab-content">
<div class="tab-pane active" id="home">
<h4>Home Panel Content</h4>
<p>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Quidem
iure quos cum, saepe reprehenderit minima quasi architecto numquam
nesciunt dicta. Qui excepturi recusandae vitae maiores, inventore
sequi? Rerum, odio omnis.
</p>
</div>
<div class="tab-pane" id="profile">
<h4>Profile Panel</h4>
<p>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Quidem
iure quos cum, saepe reprehenderit minima quasi architecto numquam
nesciunt dicta. Qui excepturi recusandae vitae maiores, inventore
sequi? Rerum, odio omnis. Lorem ipsum dolor sit amet consectetur
adipisicing elit. Alias distinctio, tempora incidunt aliquid
adipisci, minus rerum optio libero quae provident sed at
dignissimos, quia nostrum! Fuga dolorum quia hic magni.
</p>
</div>
<div class="tab-pane" id="messages">
<h4>Messages Panel</h4>
<p>
Lorem ipsum dolor sit amet consectetur, adipisicing elit. Fugiat
quos, at qui aspernatur minus animi hic sunt necessitatibus
incidunt molestiae reprehenderit ratione neque odit ipsa. Nemo
laborum consequatur adipisci beatae!
</p>
</div>
<div class="tab-pane" id="settings">
<h4>Settings Panel</h4>
<p>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Minima
possimus sed odit iste vitae, magnam amet illum laudantium ea!
Fugiat consectetur consequuntur qui eos obcaecati sequi ipsam
repellat vero voluptate.
</p>
</div>
</div>
<!-- Tabs -->
<ul id="nav-tab" class="nav">
<li class="active"><a href="#home">Home</a></li>
<li><a href="#profile">Profile</a></li>
<li><a href="#messages">Messages</a></li>
<li><a href="#settings">Settings</a></li>
</ul>
</div>












share|improve this question






















  • Works perfectly fine. Press "Run code snippet".
    – CertainPerformance
    Nov 11 at 4:01













up vote
-1
down vote

favorite









up vote
-1
down vote

favorite











So for some reason, it returns as Cannot read property 'addEventListener' of null in my console. Trying to make the tabs work. Can't find what is wrong with the code. Any help would be appreciated. Or if you could give me a better way of how to make tabs with JS.



This is my Javascript code






function onTabClick(event) {
let activeTabs = document.querySelectorAll(".active");



activeTabs.forEach(function(tab) {
tab.className = tab.className.replace("active", "");
});

// activate new tab and panel
event.target.parentElement.className += " active";
document.getElementById(event.target.href.split("#")[1]).className +=
" active";
}

var element = document.getElementById("nav-tab");
element.addEventListener("click", onTabClick, false);

And this is my HTML

<div class="container">
<!-- Tab panes -->
<div class="tab-content">
<div class="tab-pane active" id="home">
<h4>Home Panel Content</h4>
<p>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Quidem
iure quos cum, saepe reprehenderit minima quasi architecto numquam
nesciunt dicta. Qui excepturi recusandae vitae maiores, inventore
sequi? Rerum, odio omnis.
</p>
</div>
<div class="tab-pane" id="profile">
<h4>Profile Panel</h4>
<p>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Quidem
iure quos cum, saepe reprehenderit minima quasi architecto numquam
nesciunt dicta. Qui excepturi recusandae vitae maiores, inventore
sequi? Rerum, odio omnis. Lorem ipsum dolor sit amet consectetur
adipisicing elit. Alias distinctio, tempora incidunt aliquid
adipisci, minus rerum optio libero quae provident sed at
dignissimos, quia nostrum! Fuga dolorum quia hic magni.
</p>
</div>
<div class="tab-pane" id="messages">
<h4>Messages Panel</h4>
<p>
Lorem ipsum dolor sit amet consectetur, adipisicing elit. Fugiat
quos, at qui aspernatur minus animi hic sunt necessitatibus
incidunt molestiae reprehenderit ratione neque odit ipsa. Nemo
laborum consequatur adipisci beatae!
</p>
</div>
<div class="tab-pane" id="settings">
<h4>Settings Panel</h4>
<p>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Minima
possimus sed odit iste vitae, magnam amet illum laudantium ea!
Fugiat consectetur consequuntur qui eos obcaecati sequi ipsam
repellat vero voluptate.
</p>
</div>
</div>
<!-- Tabs -->
<ul id="nav-tab" class="nav">
<li class="active"><a href="#home">Home</a></li>
<li><a href="#profile">Profile</a></li>
<li><a href="#messages">Messages</a></li>
<li><a href="#settings">Settings</a></li>
</ul>
</div>












share|improve this question













So for some reason, it returns as Cannot read property 'addEventListener' of null in my console. Trying to make the tabs work. Can't find what is wrong with the code. Any help would be appreciated. Or if you could give me a better way of how to make tabs with JS.



This is my Javascript code






function onTabClick(event) {
let activeTabs = document.querySelectorAll(".active");



activeTabs.forEach(function(tab) {
tab.className = tab.className.replace("active", "");
});

// activate new tab and panel
event.target.parentElement.className += " active";
document.getElementById(event.target.href.split("#")[1]).className +=
" active";
}

var element = document.getElementById("nav-tab");
element.addEventListener("click", onTabClick, false);

And this is my HTML

<div class="container">
<!-- Tab panes -->
<div class="tab-content">
<div class="tab-pane active" id="home">
<h4>Home Panel Content</h4>
<p>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Quidem
iure quos cum, saepe reprehenderit minima quasi architecto numquam
nesciunt dicta. Qui excepturi recusandae vitae maiores, inventore
sequi? Rerum, odio omnis.
</p>
</div>
<div class="tab-pane" id="profile">
<h4>Profile Panel</h4>
<p>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Quidem
iure quos cum, saepe reprehenderit minima quasi architecto numquam
nesciunt dicta. Qui excepturi recusandae vitae maiores, inventore
sequi? Rerum, odio omnis. Lorem ipsum dolor sit amet consectetur
adipisicing elit. Alias distinctio, tempora incidunt aliquid
adipisci, minus rerum optio libero quae provident sed at
dignissimos, quia nostrum! Fuga dolorum quia hic magni.
</p>
</div>
<div class="tab-pane" id="messages">
<h4>Messages Panel</h4>
<p>
Lorem ipsum dolor sit amet consectetur, adipisicing elit. Fugiat
quos, at qui aspernatur minus animi hic sunt necessitatibus
incidunt molestiae reprehenderit ratione neque odit ipsa. Nemo
laborum consequatur adipisci beatae!
</p>
</div>
<div class="tab-pane" id="settings">
<h4>Settings Panel</h4>
<p>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Minima
possimus sed odit iste vitae, magnam amet illum laudantium ea!
Fugiat consectetur consequuntur qui eos obcaecati sequi ipsam
repellat vero voluptate.
</p>
</div>
</div>
<!-- Tabs -->
<ul id="nav-tab" class="nav">
<li class="active"><a href="#home">Home</a></li>
<li><a href="#profile">Profile</a></li>
<li><a href="#messages">Messages</a></li>
<li><a href="#settings">Settings</a></li>
</ul>
</div>








function onTabClick(event) {
let activeTabs = document.querySelectorAll(".active");



activeTabs.forEach(function(tab) {
tab.className = tab.className.replace("active", "");
});

// activate new tab and panel
event.target.parentElement.className += " active";
document.getElementById(event.target.href.split("#")[1]).className +=
" active";
}

var element = document.getElementById("nav-tab");
element.addEventListener("click", onTabClick, false);

And this is my HTML

<div class="container">
<!-- Tab panes -->
<div class="tab-content">
<div class="tab-pane active" id="home">
<h4>Home Panel Content</h4>
<p>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Quidem
iure quos cum, saepe reprehenderit minima quasi architecto numquam
nesciunt dicta. Qui excepturi recusandae vitae maiores, inventore
sequi? Rerum, odio omnis.
</p>
</div>
<div class="tab-pane" id="profile">
<h4>Profile Panel</h4>
<p>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Quidem
iure quos cum, saepe reprehenderit minima quasi architecto numquam
nesciunt dicta. Qui excepturi recusandae vitae maiores, inventore
sequi? Rerum, odio omnis. Lorem ipsum dolor sit amet consectetur
adipisicing elit. Alias distinctio, tempora incidunt aliquid
adipisci, minus rerum optio libero quae provident sed at
dignissimos, quia nostrum! Fuga dolorum quia hic magni.
</p>
</div>
<div class="tab-pane" id="messages">
<h4>Messages Panel</h4>
<p>
Lorem ipsum dolor sit amet consectetur, adipisicing elit. Fugiat
quos, at qui aspernatur minus animi hic sunt necessitatibus
incidunt molestiae reprehenderit ratione neque odit ipsa. Nemo
laborum consequatur adipisci beatae!
</p>
</div>
<div class="tab-pane" id="settings">
<h4>Settings Panel</h4>
<p>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Minima
possimus sed odit iste vitae, magnam amet illum laudantium ea!
Fugiat consectetur consequuntur qui eos obcaecati sequi ipsam
repellat vero voluptate.
</p>
</div>
</div>
<!-- Tabs -->
<ul id="nav-tab" class="nav">
<li class="active"><a href="#home">Home</a></li>
<li><a href="#profile">Profile</a></li>
<li><a href="#messages">Messages</a></li>
<li><a href="#settings">Settings</a></li>
</ul>
</div>





function onTabClick(event) {
let activeTabs = document.querySelectorAll(".active");



activeTabs.forEach(function(tab) {
tab.className = tab.className.replace("active", "");
});

// activate new tab and panel
event.target.parentElement.className += " active";
document.getElementById(event.target.href.split("#")[1]).className +=
" active";
}

var element = document.getElementById("nav-tab");
element.addEventListener("click", onTabClick, false);

And this is my HTML

<div class="container">
<!-- Tab panes -->
<div class="tab-content">
<div class="tab-pane active" id="home">
<h4>Home Panel Content</h4>
<p>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Quidem
iure quos cum, saepe reprehenderit minima quasi architecto numquam
nesciunt dicta. Qui excepturi recusandae vitae maiores, inventore
sequi? Rerum, odio omnis.
</p>
</div>
<div class="tab-pane" id="profile">
<h4>Profile Panel</h4>
<p>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Quidem
iure quos cum, saepe reprehenderit minima quasi architecto numquam
nesciunt dicta. Qui excepturi recusandae vitae maiores, inventore
sequi? Rerum, odio omnis. Lorem ipsum dolor sit amet consectetur
adipisicing elit. Alias distinctio, tempora incidunt aliquid
adipisci, minus rerum optio libero quae provident sed at
dignissimos, quia nostrum! Fuga dolorum quia hic magni.
</p>
</div>
<div class="tab-pane" id="messages">
<h4>Messages Panel</h4>
<p>
Lorem ipsum dolor sit amet consectetur, adipisicing elit. Fugiat
quos, at qui aspernatur minus animi hic sunt necessitatibus
incidunt molestiae reprehenderit ratione neque odit ipsa. Nemo
laborum consequatur adipisci beatae!
</p>
</div>
<div class="tab-pane" id="settings">
<h4>Settings Panel</h4>
<p>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Minima
possimus sed odit iste vitae, magnam amet illum laudantium ea!
Fugiat consectetur consequuntur qui eos obcaecati sequi ipsam
repellat vero voluptate.
</p>
</div>
</div>
<!-- Tabs -->
<ul id="nav-tab" class="nav">
<li class="active"><a href="#home">Home</a></li>
<li><a href="#profile">Profile</a></li>
<li><a href="#messages">Messages</a></li>
<li><a href="#settings">Settings</a></li>
</ul>
</div>






javascript addeventlistener






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 11 at 4:00









Igor Voytt

1




1












  • Works perfectly fine. Press "Run code snippet".
    – CertainPerformance
    Nov 11 at 4:01


















  • Works perfectly fine. Press "Run code snippet".
    – CertainPerformance
    Nov 11 at 4:01
















Works perfectly fine. Press "Run code snippet".
– CertainPerformance
Nov 11 at 4:01




Works perfectly fine. Press "Run code snippet".
– CertainPerformance
Nov 11 at 4:01












1 Answer
1






active

oldest

votes

















up vote
0
down vote













The problem here is your JavaScript is running before the browser has finished creating those HTML elements. This is because your JavaScript is probably located above your HTML code. There are two ways to fix this. One is to move your JavaScript to just before the closing </body> tag, or the better way is to wrap it in a call to document.addEventListener("DOMContentLoaded", function() {...}); like so:



document.addEventListener("DOMContentLoaded", function() {
document.querySelectorAll("#nav-tab a").forEach(function(element) {
element.addEventListener("click", onTabClick, false);
});
});


The second problem I noticed after I had fixed the first is that since your event handler is applied to the <ul> element, when you get to document.getElementById(event.target.href.split("#")[1]).className += " active";, you will notice that if you clicked on the <ul> element and not one of the links, you would get an error saying Cannot read property 'split' of undefined. Instead, you want to be applying the event listener to the links only, so I have wrapped it in a call to document.querySelectorAll, which will give you just the links, which you can loop over and add event listeners to.






share|improve this answer





















    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














     

    draft saved


    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53245729%2fcannot-read-property-addeventlistener-of-null-while-trying-to-make-tabs-work%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    0
    down vote













    The problem here is your JavaScript is running before the browser has finished creating those HTML elements. This is because your JavaScript is probably located above your HTML code. There are two ways to fix this. One is to move your JavaScript to just before the closing </body> tag, or the better way is to wrap it in a call to document.addEventListener("DOMContentLoaded", function() {...}); like so:



    document.addEventListener("DOMContentLoaded", function() {
    document.querySelectorAll("#nav-tab a").forEach(function(element) {
    element.addEventListener("click", onTabClick, false);
    });
    });


    The second problem I noticed after I had fixed the first is that since your event handler is applied to the <ul> element, when you get to document.getElementById(event.target.href.split("#")[1]).className += " active";, you will notice that if you clicked on the <ul> element and not one of the links, you would get an error saying Cannot read property 'split' of undefined. Instead, you want to be applying the event listener to the links only, so I have wrapped it in a call to document.querySelectorAll, which will give you just the links, which you can loop over and add event listeners to.






    share|improve this answer

























      up vote
      0
      down vote













      The problem here is your JavaScript is running before the browser has finished creating those HTML elements. This is because your JavaScript is probably located above your HTML code. There are two ways to fix this. One is to move your JavaScript to just before the closing </body> tag, or the better way is to wrap it in a call to document.addEventListener("DOMContentLoaded", function() {...}); like so:



      document.addEventListener("DOMContentLoaded", function() {
      document.querySelectorAll("#nav-tab a").forEach(function(element) {
      element.addEventListener("click", onTabClick, false);
      });
      });


      The second problem I noticed after I had fixed the first is that since your event handler is applied to the <ul> element, when you get to document.getElementById(event.target.href.split("#")[1]).className += " active";, you will notice that if you clicked on the <ul> element and not one of the links, you would get an error saying Cannot read property 'split' of undefined. Instead, you want to be applying the event listener to the links only, so I have wrapped it in a call to document.querySelectorAll, which will give you just the links, which you can loop over and add event listeners to.






      share|improve this answer























        up vote
        0
        down vote










        up vote
        0
        down vote









        The problem here is your JavaScript is running before the browser has finished creating those HTML elements. This is because your JavaScript is probably located above your HTML code. There are two ways to fix this. One is to move your JavaScript to just before the closing </body> tag, or the better way is to wrap it in a call to document.addEventListener("DOMContentLoaded", function() {...}); like so:



        document.addEventListener("DOMContentLoaded", function() {
        document.querySelectorAll("#nav-tab a").forEach(function(element) {
        element.addEventListener("click", onTabClick, false);
        });
        });


        The second problem I noticed after I had fixed the first is that since your event handler is applied to the <ul> element, when you get to document.getElementById(event.target.href.split("#")[1]).className += " active";, you will notice that if you clicked on the <ul> element and not one of the links, you would get an error saying Cannot read property 'split' of undefined. Instead, you want to be applying the event listener to the links only, so I have wrapped it in a call to document.querySelectorAll, which will give you just the links, which you can loop over and add event listeners to.






        share|improve this answer












        The problem here is your JavaScript is running before the browser has finished creating those HTML elements. This is because your JavaScript is probably located above your HTML code. There are two ways to fix this. One is to move your JavaScript to just before the closing </body> tag, or the better way is to wrap it in a call to document.addEventListener("DOMContentLoaded", function() {...}); like so:



        document.addEventListener("DOMContentLoaded", function() {
        document.querySelectorAll("#nav-tab a").forEach(function(element) {
        element.addEventListener("click", onTabClick, false);
        });
        });


        The second problem I noticed after I had fixed the first is that since your event handler is applied to the <ul> element, when you get to document.getElementById(event.target.href.split("#")[1]).className += " active";, you will notice that if you clicked on the <ul> element and not one of the links, you would get an error saying Cannot read property 'split' of undefined. Instead, you want to be applying the event listener to the links only, so I have wrapped it in a call to document.querySelectorAll, which will give you just the links, which you can loop over and add event listeners to.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 11 at 4:15









        Sam Leatherdale

        11517




        11517






























             

            draft saved


            draft discarded



















































             


            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53245729%2fcannot-read-property-addeventlistener-of-null-while-trying-to-make-tabs-work%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Bressuire

            Vorschmack

            Quarantine