Search code examples
javascriptnullgetelementsbytagname

Javascript, variable is null - cannot call method 'getElementsByTagName' of null


I have some basic JavaScript which I'm working around with. It works fine on my localhost by throws an error when implemented on the web. I get the following error in the dev tools using firefox or crome.

Uncaught TypeError: Cannot call method 'getElementsByTagName' of null.

Any help much appreciated. Thanks

<!DOCTYPE html>
<html>

    <head>
        <title>Title</title>
        <style type="text/css">
            body {
                background-color: beige;
                margin: 0;
            }
            #main li {
                width: 100px;
                padding: 5px 0;
            }
        </style>
    </head>

    <body>
        <div id="main">
            <ul>
                <li>A list item</li>
                <li>B list item</li>
                <li>C list item</li>
            </ul>
        </div>
        <script type="text/javascript">
            var insert = document.getElementById("main");
            insert.getElementsByTagName("li")[1].style.borderRight = "1px solid blue";
        </script>
    </body>

</HTML>

Solution

  • The above code looks good. there are no errors. The only possible condition where this can't work is that you may have forgotten to change the original id name which you are using in your project with this demo id i.e main.

    It is really hard to say. Check by doing the following

    • change variable name i.e insert .
    • keep the javascript in script tags like <script></script>.
    • or there could be some hidden characters.

    You are enclosing your html tag with caps i.e HTML. I suppose this might be the problem.