Skip to content
Advertisement

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?

Advertisement

Answer

onmouseover="showDescription('Text', 'Text with HTML tags in them<br />More text');" 

Like with all attribute values, you must HTML-encode &, <, and the attribute delimiter (" here). The fact that it’s JavaScript inside the attribute value makes no difference; the HTML attribute value is decoded before JavaScript gets a look at it.

onmouseover="showDescription('Text', 'Text with HTML tags in them&lt;br />More text');" 

This is in contrast to a <script> element, whose contents are CDATA and thus not &-escaped in HTML4. In XHTML there are no CDATA elements; you can add a <![CDATA[ section to make XHTML behave the same, but it’s usually simpler for both script elements and event handler attributes to just avoid the problem by never using a & or < character. In a string literal another escape is available which you can use to get around this:

onmouseover="showDescription('Text', 'Text with HTML tags in themx3Cbr />More text');" 
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement