Problem with HTML and JS

Asked by Karan Singh about a month ago


I'm trying to access h1 element from HTML by using JS: "const heading = document.querySelector('h1') console.log(heading)" but it is showing error in the console on VSCode and I have checked everything, I have tried everything but nothing seems to fix my problem. What should I do?

1 Answer


    Here are some things you can check:

    Make sure that your HTML file has an h1 element. You can do this by opening your HTML file and checking that there is an h1 tag present.

    Make sure that your JavaScript file is properly linked to your HTML file. You can do this by checking that your JavaScript file is included in your HTML file using the <script> tag.

    Make sure that your JavaScript code is being executed after the HTML page has loaded. You can do this by wrapping your code in an event listener for the DOMContentLoaded event, like this:


    document.addEventListener('DOMContentLoaded', () => { const heading = document.querySelector('h1'); console.log(heading); }); Check the console for any other error messages that might be causing your code to fail.

    If none of these steps work, try posting your full HTML and JavaScript code to get more help on identifying the problem.


    Sanjay Singh


    Your answer