skip to Main Content

I have been trying to create a html file in java script but it is not working with many errors. please help.

Please see code attached in the screenshot. I am fairly new to this and am not sure if it is a setting issue on VScode or if it’s another issue?enter image description here

3

Answers


  1. current file is JS file.
    What are you trying to do with html in your js file? I think the code like now is the code used in the .html extension. I think changing the extension to .html will solve the problem.

    Login or Signup to reply.
  2. I think you might be a bit confused. There are a couple of ways to do this, but I’ll give you two for now:

    1. When you want to write HTML in JS file, you have to have an HTML file separate and then target the HTML elements with DOM using javascript.

    2. Another approach is to add in your HTML file and then add your JavaScript logic within it.

    This is an example of how you can add javascript to your HTML file. I hope this helps.

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Dynamic HTML with JavaScript</title>
    </head>
    <body>
    
    
    // JavaScript, your calling elements within HTML using DOM
    <script>
        // Create a button element
        const buttonElement = document.createElement('button');
    
        // Set button properties
        buttonElement.textContent = 'Click me!';
        buttonElement.style.backgroundColor = 'blue';
        buttonElement.style.color = 'white';
    
        // Add a click event listener to the button
        buttonElement.addEventListener('click', function () {
            alert('Button clicked!');
        });
    
        // Append the button to the body of the document
        document.body.appendChild(buttonElement);
    </script>
    
    </body>
    </html>
    

    Happy coding!

    Login or Signup to reply.
  3. change filename test.js to test.html

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search