Home > Back-end >  Searching and referencing html files in js file
Searching and referencing html files in js file

Time:07-22

So I was doing some grasshopper HTML learning and thought that I could replicate it...

Oh how naive, I was...

The intention was to change text in a button when clicked

Here is the reference JS code

let button1 = document.getElementById('button1');
button1.addEventListener('click', () => {
    button1.textContent = 'Clicked!';
});

and html reference

<html>
    <body>
        <button id='button1'>Fresh Button1</button>
    </body>
</html>

Unfortunately, however much I tried to make it work, I kept getting told off by VS Code that

Uncaught ReferenceError ReferenceError: document is not defined

I don't know how to fix it, I've tried everything, scripting it IN the HTML file, making a variable that would pull it from the html file,... (sub-question: is it possible to reference a document in JS, like the src="" in HTML?)

I've spent the better part of my evening grinding on this and want to throw my pc out of the window. I don't know if it's just a syntax error or if I'm using it wrong... I just don't know.

Please help, thanks

Sincerely, Seven

CodePudding user response:

I've spent the better part of my evening grinding on this and want to throw my pc out of the window. I don't know if it's just a syntax error or if I'm using it wrong... I just don't know.

Don't throw your pc out the window. There's no syntax error. You've done everything right.

I don't know how to fix it

Trust me, there's nothing to fix.

Here is your code below.

It works:

let button1 = document.getElementById('button1');

button1.addEventListener('click', () => {
    
    button1.textContent = 'Clicked!';
});
<button type="button" id="button1">Fresh Button1</button>

CodePudding user response:

[edit] Deleted my wrong answer - sorry!

  • Related