Coolcrab
Coolcrab

Reputation: 2723

javascript show variable in html

I'm trying to make a money display for a form which I am making, now I found this script on the web: http://jsfiddle.net/QQGfc/ And I'm trying to implement it into my code like this: (but it's not displaying the text.)

</script>

<script type="text/javascript">
document.getElementById("MyEdit").innerHTML = "My new text!";
</script>

With this in the body

<?php
include'includes/header.php'; 
include'includes/slider.php'; //carousel
?>


<h2>Contact Information</h2>


<div id="MyEdit">
    This text will change
</div>

Ay idea whats going wrong?

Upvotes: -1

Views: 100

Answers (2)

Mehran Hatami
Mehran Hatami

Reputation: 12961

you should do it after the DOM is completely loaded:

<script type="text/javascript">
    window.addEventListener("load", function(){
        document.getElementById("MyEdit").innerHTML = "My new text!";
    });
</script>

Upvotes: 0

Quentin
Quentin

Reputation: 943207

You imply that the JavaScript is in the <head>.

When it runs, the <body> hasn't been parsed, so the element you are trying to modify does not exist.

Either:

  • Move the script to after the <div> you are trying to modify.
  • Wrap the script in a function and call that function after the <div> exists (e.g. by binding it as a load event handler).

Upvotes: 6

Related Questions