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 >
<div >
<form >
<input type="text"
placeholder="Search Location .."/>
<button type="submit"
>
<i ></i>
</button>
</form>
<ul >
<li >Paris</li>
<li >Las Vegas</li>
<li >Japan</li>
<li >Sfax</li>
</ul>
</div>
</div>
<script src = "main.js" ></script>`
.............................................................................
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";
}
});
CodePudding user response:
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 >
...
for more details about CSS selectors see this https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors
CodePudding user response:
You don't have a .form class in your html
<div >
<div >
<form >
<input type="text"
placeholder="Search Location .."/>
<button type="submit"
>
<i ></i>
</button>
</form>
<ul >
<li >Paris</li>
<li >Las Vegas</li>
<li >Japan</li>
<li >Sfax</li>
</ul>
</div>
</div>
<script src = "main.js" ></script>
Remove the . if you want to query the DOM for a tag
const form = document.querySelector('.form');