Daniel
Daniel

Reputation: 11

Vue2 error 'classList' of null error

So i am writhing a component in Vue. Just a simple navigation. Withing methods i made a active script. i also made a "created" loadfunction script and console the element of it.

It gives me the following error in the console:

TypeError: Cannot read property 'classList' of null
at VueComponent.created (eval at <anonymous> (app.js:1002), <anonymous>:23:67)
at callHook (eval at <anonymous> (app.js:672), <anonymous>:2275:21)
at VueComponent.Vue._init (eval at <anonymous> (app.js:672), <anonymous>:3758:5)
at new VueComponent (eval at <anonymous> (app.js:672), <anonymous>:3922:12)
at createComponentInstanceForVnode (eval at <anonymous> (app.js:672), <anonymous>:3117:10)
at init (eval at <anonymous> (app.js:672), <anonymous>:2925:45)
at createComponent (eval at <anonymous> (app.js:672), <anonymous>:4656:9)
at createElm (eval at <anonymous> (app.js:672), <anonymous>:4599:9)
at createChildren (eval at <anonymous> (app.js:672), <anonymous>:4724:9)
at createElm (eval at <anonymous> (app.js:672), <anonymous>:4632:9)

Weirdly enough when i remove .classList it still gives a null value and not a empty array.

Here is my code for the component (note this is in dutch):

<script>
export default {
    name: 'frontnav',
    data () {
        return {
            aantal: [
                'Aankomende Gasten',
                'In Huis',
                'Vertrekkende Gasten',
                'Dag Gasten'],
            dag: [
                'Vandaag',
                'Morgen',
                'Overmorgen',
                'Deze Week',
                'Volgende Week'],
            active: 'Aankomende Gasten'
        }
    },
    methods: {
        makeActive: function (aantal) {
            this.active = aantal;
            let el = document.querySelector('nav tr a:first-child');
            document.querySelector('.' + item).classList.add('active');
        },
        loadfunction: function () {
           const el = document.querySelector('nav a:first-child');
           el.classList.add('active');
        }
    },
    created () {
       this.loadfunction();
        console.log(document.querySelector('nav tr a:first-child').classList);
    }
}

Upvotes: 1

Views: 1617

Answers (2)

Daniel
Daniel

Reputation: 11

just found out that const el = document.querySelector('nav a:first-child');

All making it a collection. :/

it should be

const el = document.querySelectorAll('nav a:first-child');

Upvotes: 0

Jonatas Walker
Jonatas Walker

Reputation: 14168

Change created() to mounted().

If you're manipulating DOM, you'll be better wait for it.

Upvotes: 1

Related Questions