0

I am trying to simply update a span tag usign the following method...

<script type="text/javascript">

document.getElementById("myspan").innerHTML="newtext";  

</script>

<span id="myspan"> hereismytext </span>

But i am getting the following error:

document.getElementById("myspan") is null

Any ideas as to what is causing this?

Cheers

Rich

3 Answers 3

2

That is because you need to add that javascript after the element (the element has to be first created in DOM for the javascript to see it):

<span id="myspan"> hereismytext </span>
<script type="text/javascript">
    document.getElementById("myspan").innerHTML="newtext";  
</script>

Or use window.onload:

<script type="text/javascript">
    window.onload = function(){
        document.getElementById("myspan").innerHTML="newtext";  
    }
</script>
<span id="myspan"> hereismytext </span>
Sign up to request clarification or add additional context in comments.

1 Comment

It's not because you need to put the Javascript after the element. You need the javascript to run after the element is known to the browser, which is different.
0

Try putting your JavaScript code into a function, and calling it in the page onload handler - as things stand, if you have your script tag at the top of the page then the DOM (and therefore your span) won't exist at the time your code gets executed:

<script type="text/javascript">
funcion loaded(){
    document.getElementById("myspan").innerHTML="newtext";  
}
</script>

<body onload="loaded()">
    ...

Comments

0

When you're communicating with the DOM, you need to make sure that it exists/is ready to be modified. In your example, you're changing an element with the id myspan before it exists (the javascript is running before the html) and therefore the browser cannot find it. You either need to put it after:

<!-- HTML -->
<script type="text/javascript">
//change html
</script>

Or check wait until it's ready.

window.onload = function() {
    //change html
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.