0

i have used preventDefault() but thats not working here is My Code

btnBookNameSearch.addEventListener("click", (e) => {
    e.preventDefault();
    const searchValue = btnBookNameSearch.value.toLowerCase().trim();
 
    allPgBooks.forEach((product) => {
        if (product.name == searchValue) {
            allPgBooksE2.innerHTML = '';
            if (allPgBooksE2) { 

there is a mistake i am doing in the first two line of code above but idk how to fix ....the Error i am getting is ....Cannot read properties of null (reading 'addEventListener') ...

enter image description here

Drag13
  • 5,859
  • 1
  • 18
  • 42
khan ubaid
  • 13
  • 3
  • Take a look at [this answer](https://stackoverflow.com/a/34281265/16688813) – Tom Dec 08 '21 at 16:59
  • 1
    Chances are your loading the script in your HTML head, a common method of loading scripts these days is to place before the body closing tag.. `....

    `...

    – Keith Dec 08 '21 at 17:06

3 Answers3

1

Your btnBookNamsSearch is null. Probably you trying to find the button by wrong id or selector.

Alex Shinkevich
  • 348
  • 1
  • 5
0

It just means that the variable btnBookNameSearch is empty. It couldn't find the element that supposed to be inside that variable. It could be typo in the way you retrieved the element, e.g. document.querySelector('.element-class').

Ludolfyn
  • 1,806
  • 14
  • 20
0

use DOMContentLoaded event. Add your code inside the callback function

document.addEventListener("DOMContentLoaded", function(event) {
    // Your code to run, DOM is loaded and ready
   btnBookNameSearch.addEventListener("click", (e) => {
   e.preventDefault();
   const searchValue = btnBookNameSearch.value.toLowerCase().trim();
   .....
   .....
});
Deepu Reghunath
  • 8,132
  • 2
  • 38
  • 47