Why is the html attribute returned as "htmldecoded" even though it is encoded in the html source?

I am using the html attribute header to set some hints like this:

 <a href... title="Go to next chapter">Go</a>

      

Then the jquery plugin goes through all the [title] attributes and makes pretty tooltips. A very simplified new div created for the link above

<div style="position:absolute...">Go to next chapter</div>

      

The problem is that the title is user-editable, so he can write whatever he wants. At first I thought the html encoding was ok, but it turned out that I was wrong. if I have

<a id="a" title="&lt;script&gt;alert(10);&lt;/script&gt">Go</a>

      

then the div prompt looks like this:

<div style="position:absolute..."><script>alert(10)</script></div>

      

1) Why does the browser ask for the title attribute when asking for its value?

2) And how can I solve this? (I know one solution is double html encoding, but it's awfull)

How to test it: consider this code

<html>  
 <body>  
  <!-- encoding once, this doesn't work -->
  <a id="a" title="&lt;script&gt;alert(10);&lt;/script&gt">atitle</a>  
  <!-- encoding twice, this works -->
  <a id="b" title="&amp;lt;script&amp;gt;alert(10);&amp;lt;/script&amp;gt">btitle</a>  

  <script>  
   function w(x){ document.write(x.attributes["title"].value);}  
   w(a);  // shows alert
   w(b);  // outputs it correctly into the page
  </script>  
 </body>  
</html>

      

0


source to share


1 answer


1) The attribute value is the decoded value - this is the only way that makes sense if you think about it. If you set the javascript value to "\ n" then be warned, do you want to return "\ n" or a real newline? The title attribute is text ... you just need to HTML code to write it.

2) You can code it twice, or you can use the text node:



var node = document.createTextNode(x.attributes['title'].value);
document.appendChild(node);

      

This is the preferred way, then spider / non-javascript browsers will see the correct title attribute.

+1


source







All Articles