user1163722
user1163722

Reputation:

Why won't my line break become inactive with JavaScript?

I tried using JavaScript to turn off the effect of a <BR/> tag when my page loaded, but for some reason, it isn't working. I feel like I made some sort of error, here's my html:

<HTML>
<HEAD>

<SCRIPT type="text/javascript">

var brTag = document.getElementById('newline');
brTag.style.display = 'none';

</SCRIPT>
</HEAD>

<BODY>

Line 1 <BR id = "newline" />
Line 2

</BODY>
</HTML>

Upvotes: 0

Views: 95

Answers (2)

pete
pete

Reputation: 25081

What our esteemed colleagues are saying is to either do this:

<html>
    <head>
        <script type="text/javascript">
            window.onload = function () {
                var brTag = document.getElementById('newline');
                brTag.style.display = 'none';
            };
        </script>
    </head>
    <body>
        Line 1 <br id="newline" />
        Line 2
    </body>
</html>

or this:

<html>
    <head>
    </head>
    <body>
        Line 1 <br id="newline" />
        Line 2
        <script type="text/javascript">
            var brTag = document.getElementById('newline');
            brTag.style.display = 'none';
        </script>
    </body>
</html>

That way <br id="newline" /> exists in the DOM when your code is executed. As it stands now, you are executing your code prior to <br id="newline" /> being added to the DOM tree.

Upvotes: 1

John Pick
John Pick

Reputation: 5650

You're referencing newline before it is declared. Try running the script after creating the element (i.e., either later in the file, or inside a function that is called later in the file)

Upvotes: 1

Related Questions