Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript error – Event Listener error on page load

i am working on a weather app and i’m getting this error once the page loads
"Uncaught TypeError: Cannot read property ‘addEventListener’ of null" on line 36

here is the Code Snippet for the Html :

<div class="weather - app">
          <div class="panel">
            <form >
                <input type="text"
                       class="search"  
                       placeholder="Search Location .."/>
                <button type="submit"
                        class="submit">
                    <i class="fa fa-search"></i>
                </button>
            </form>
            <ul class="cities">
                <li class="city">Paris</li>
                <li class="city">Las Vegas</li>
                <li class="city">Japan</li>
                <li class="city">Sfax</li>
            </ul>
            
        </div>
    </div>
    <script src = "main.js" ></script>`

…………………………………………………………………..

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

and for the main.js :


const app = document.querySelector('.weather-app');
const form = document.querySelector('.form');
const search = document.querySelector('.search');
const btn = document.querySelector('.submit');
const cities = document.querySelectorAll('.city');



//add sumbit event to the form
form.addEventListener('submit', (e) => {
    e.preventDefault();

    //if input field(search bar) empty throw an alert
    if (search.value.length == 0) {
        alert('Please type in a City name !');
    } else {
        //change default city name to the one written in search bar 
        cityInput = search.value;
        search.value = "";
        app.style.opacity = "0";
    }
});

>Solution :

the querySelector uses the CSS selectors to find an element in your page,
the selector you passed is .form which means find an element with a class called form and this does not appear in your HTML anywhere, so the correct selector is ‘form’ without a .
since . represents a class search

so the full code is

const form = document.querySelector('form');

or you can add class to your form

<form class="form">
...

for more details about CSS selectors see this
https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading