Variable returning null only in Firefox

Asked

Viewed 57 times

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 me the error :

TypeError: cta is null

Does anyone know what it can be?

I’m calling him 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());
  • Can you make an example working here or in jsFiddle? What happens if var cta = document.querySelector('.cta'); is also inside that load?

  • What is version of your Firefox? I have tested now in version 47.0.2 is worked correctly. In the Mozilla documentation itself https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector it is possible to find that the Mozilla supports querySelector

  • You could put in a bigger piece of code so we can analyze it better?

  • It would be very difficult to put in jsFiddle and yes really if I put this piece of code in Firefox it works, I will update the question with the full code.

1 answer

1


If your code is on <head>, it is loaded before the <body>. So, when you select an element outside of some event that guarantees the loading of the DOM, you will have as return null, since 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 event callback load in the object window, or the event Domcontentloaded of the object Document.

Example in Jsfiddle - Return correct - Load Type: No wrap in Head

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

Example in Jsfiddle - Return correct - Load Type: No wrap in Body

  • Wow. That’s right! Gzuz that amateur mistake mine. Thank you so much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.