-2
<script>
document.getElementById("comment").innerHTML="<?php echo 'foo bar'; ?>";
</script> 
<div id="comment"></div>

This should give the word "foo bar" in the div element,but its not.Do not know where i'm going wrong. Please help.

1
  • i do not know about this, but probably the php withing the quotes will get included in the HTML and not parsed. ? Commented Jul 24, 2011 at 8:23

2 Answers 2

1

You are trying to use the comment element :

document.getElementById("comment").innerHTML="...";

Before it is declared :

<div id="comment"></div>

And firebug shows the following error :

   
(source: pascal-martin.fr)


You should :

  • First, create the element in your HTLM
  • And, only after, use it :
    • Either by changing the order you are doing things in your code,
    • Or waiting until the HTML page is fully loaded to execute Javascript.


If you choose the first solution, your code will look like this :

<div id="comment"></div>
<script>
    document.getElementById("comment").innerHTML="<?php echo 'foo bar'; ?>";
</script> 

And it will work :

  • The foo bar string will be visile
  • And there won't be any JS error anymore.

   
(source: pascal-martin.fr)

Sign up to request clarification or add additional context in comments.

Comments

1

The script needs to go below the div, as it's trying to populate a div that hasn't been inserted into the DOM yet.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.