Variable returning null only in Firefox

1

I have the following piece of code:

var cta = document.querySelector('.cta');

In Chrome / Opera it returns the element correctly, only in Firefox it is returned the error:

TypeError: cta is null

Does anyone know what it can be?

I'm calling it via:

window.addEventListener('load', () => {
    cta.style.opacity = 1;
});

Complete code:

var cta = document.querySelector('.cta');

function box() {
    if(cta) {
        var vitrine = [].slice.call(document.querySelectorAll('.vitrine'));
        for(var i = 0; i < vitrine.length; i++) {
            vitrine[i].style.height = window.getComputedStyle(vitrine[i]).width;
        }
    }
}

box();

window.addEventListener('load', () => {
    cta.style.opacity = 1;
});

window.addEventListener('resize', () => box());
    
asked by anonymous 28.12.2016 / 14:36

1 answer

1

If your code is in <head> , it is loaded before <body> . So when you select an element outside of an event that guarantees DOM loading, you'll have null as the element does not yet exist.

Example in JsFiddle - Return null - Load Type: No wrap in Head

You can change this by storing your element in the variable, within the load event callback in the window object, or the DOMContentLoaded event document object.

Example in JsFiddle - Correct Return - Load Type: No wrap in Head

Or putting your code inside body , at the bottom of the page:

Example in JsFiddle - Correct Return - Load Type: No wrap in Body

    
28.12.2016 / 15:19