0

My code isn't working, I am getting an error: Uncaught TypeError: Cannot read property 'addEventListener' of null How to make this code work?

<!DOCTYPE html>

<html>
    <head>
        <title>Fashion Closet</title>
    </head>
    <body>
        <header>
            <h1>Fashion Closet</h1>
            <p>Unique look for daily routine</p>
        </header>
    </body>
    <div>
        <button id="create-look">Create a new look</button>
    </div>
    <script src="/scripts/bundle.js"></script>
</html>

and here is JS, with the eventListener which throws error by execution

import uuidv4 from 'uuid/v4'

// defining the looks array

let looks = []

// creating a new look

const createLook = () => {
    const lookId = uuidv4()
    looks.push({
        id: lookId,
        title: ''
    })
    saveLooks()

    return lookId
}

// Creating an event listener

document.getElementById("#create-look").addEventListener("click", (e) => {

  //calling a function 
    const id = createLook()
    location.assign(`/looks.html#${id}`)
  })
yavnelf
  • 5
  • 4
  • 1
    perhaps your javascript is loading and running BEFORE the HTML is loaded - specifically before that element is in the DOM – Jaromanda X Sep 23 '20 at 06:49
  • Though, it looks like you load the script at the end of the body - so, the code as presented (after removing the import statement for testing) will work - perhaps the code in the question is not indicative of the real code you have an issue with – Jaromanda X Sep 23 '20 at 06:51
  • There is only one reason `document.getElementById` returns `null`: There was no element with that `id` as of when the function was called. In the above, you've shown your `script` tag for the code after the `button`'s tag, but if it were really that way in your real code, `document.getElementById` wouldn't return `null`. – T.J. Crowder Sep 23 '20 at 06:52
  • Check for DOM loaded before doing manipulation – Shubham Srivastava Sep 23 '20 at 06:53

0 Answers0