Reputation: 5183
For example I have such string in php:
$str='<img title="title of image" src="../somepic.gif" alt="some pic image" class="someclass" style="somestiles" onload="alert(this)" />';
//it can be anything: '<br>123<P><script>' or '123</script>' (even with newlines \r and \n and other special symbols)
And I need it to show only after click:
<?php
echo'<div>
<textarea onclick="this.parentNode.innerHTML=this.value">',htmlspecialchars($str),'</textarea>
</div>';
?>
As we can see, js replaces texarea element with what was stored in $str variable and placed in "<textarea>" value as text.
I need to know how to achieve this without using textarea elements for storing data for JS. (now i'm using hidden textareas, but I doubt that such method is correct)
Upvotes: 1
Views: 345
Reputation: 268344
Just store the HTML as a (properly-escaped) string:
var foo = document.getElementById("foo"),
html = "<img src='http://placekitten.com/100/100' onclick='alert(1);' />";
if (foo.addEventListener) {
foo.addEventListener("click", setInner, false);
} else if(foo.attachEvent) {
foo.attachEvent("onclick", setInner);
}
function setInner () {
foo.innerHTML = html;
}
Demo: http://jsfiddle.net/UAL8P/
Upvotes: 2