Thursday, June 6, 2024
 Popular · Latest · Hot · Upcoming
32
rated 0 times [  33] [ 1]  / answers: 1 / hits: 54952  / 15 Years ago, sat, november 28, 2009, 12:00:00

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?


More From » html

 Answers
289
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'); 

[#98202] Wednesday, November 25, 2009, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
gabriel

Total Points: 323
Total Questions: 107
Total Answers: 108

Location: Federated States of Micronesia
Member since Sun, May 16, 2021
3 Years ago
gabriel questions
Sun, Feb 14, 21, 00:00, 3 Years ago
Tue, Dec 8, 20, 00:00, 4 Years ago
Mon, Jun 8, 20, 00:00, 4 Years ago
Tue, May 19, 20, 00:00, 4 Years ago
;