Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using HTML tags in JavaScript strings while complying with W3C rules

Here's my code:

<a href="#">
    <img src="myimage.jpg" 
     onmouseover="showDescription(
          'Text', 'Text with HTML tags in them<br />More text');" 
     onmouseout="revertDescription();" 
     alt="Image description">

The W3C Markup Validator doesn't like this. It doesn't want HTML tags inside my JavaScript code. Here's the error message it produces if I attempt this:

character "<" is the first character of a delimiter but occurred as data

How can I fix this while making sure that my page doesn't mess up if I pass the HTML tag-containing string to document.getElementById('myElement').innerHTML?

like image 403
Pieter Avatar asked Apr 12 '26 03:04

Pieter


1 Answers

You could wrap your functions inside separate <script>...</script> tags somewhere else in the document, and there use ...

<script>
//<![CDATA[
    ...code...
//]]>
</script>

From http://javascript.about.com/library/blxhtml.htm:

To fix this problem wer can do one of two things. The simplest way, particularly if the Javascript contains more than just one or two lines, is to make the Javascript external to the page resulting in their being nothing between the script tags to stop the page validating.

If it is just one or two lines then it is probably not worth making an external script so you will want to leave the content between the script tags and tell the validator that this is to be ignored. We do this by placing the Javascript code within a CDATA tag like this ...

like image 88
miku Avatar answered Apr 14 '26 16:04

miku



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!