user1647710
user1647710

Reputation: 55

Javascript.innerHTML is commenting out everything that starts with <?

Does anyone know how can I avoid this text from being commented out when using .innerHTML to display results?

document.getElementById("Final-Result").innerHTML = "This text will appear, <? while this will be commented out ?>";

You can try it out here http://www.w3schools.com/js/tryit.asp?filename=tryjs_comments1

Edit: I need the PHP tags to be there, not for functionality reasons but rather displaying an HTML <code> block with the code snippet, problem is, if I replaced < and > with &lt; and &gt; - the whole HTML block will be represented as text. The other approach is to use RegExp to replace (all) <? and ?> occurrences What would such a RegExp be like?

Thanks.

Upvotes: 0

Views: 652

Answers (4)

user2952238
user2952238

Reputation: 787

<? and ?> are shorthand for PHP tags. Why do you want them in an HTML string? Try to wrap them in quotes.

Upvotes: 0

user663031
user663031

Reputation:

Use innerText or textContent instead of innerHTML, since it's not HTML.

Upvotes: 1

user3687550
user3687550

Reputation: 57

Hi just remove the php tag

<!DOCTYPE html>
<html>
<body>

<h1 id="myH"></h1>
<p id="myP"></p>

<script>
// Change heading:
document.getElementById("myH").innerHTML = "My First Page";
// Change paragraph:
document.getElementById("myP").innerHTML = "This text will appear, < while this will be commented out >";
</script>

</body>
</html>

Upvotes: 0

Ruben-J
Ruben-J

Reputation: 2693

This is because you need to encode < > else its trying to parse it as htmltags.

&lt; =  < 
&gt; =  >

http://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references

In your case this will be written as

document.getElementById("Final-Result").innerHTML = "This text will appear, &lt;? while this will be commented out ?&gt;";

Upvotes: 2

Related Questions