Search This Blog

Thursday, December 16, 2010

Display tags as literal strings in JavaScript

When using JavaScript statements such as document.write("<table>") to display HTML tags as literal strings, browsers will mistake that we want to insert the tags into the page structure instead of displaying them as text. For example:

<script type="text/javascript">
  //this won't display the text "<table>" and "</table>"
  document.write("<table>");  
  document.write("</table>");
</script>

The above script won't work. The screen will show nothing because the browser interprets the string as HTML table tags. To work around this, split the string that contains tags to be displayed into parts:

<script type="text/javascript">  
  document.write("<ta" + "ble>");  
  document.write("</tab" + "le>");
</script>

Happy coding and don't forget to comment :)

No comments:

Post a Comment