Javascript DOM How to - ?Append link element with encoded data








Question

We would like to know how to Append link element with encoded data.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>
window.onload=function(){<!--  ww  w  .  j av  a2  s .  c  o m-->
    var css = '*{color:red;}';
    var link = document.createElement('link');
    link.rel = 'stylesheet';
    link.href = 'data:text/css;charset=UTF-8,' + encodeURIComponent(css);
    document.getElementsByTagName('head')[0].appendChild(link);
}
</script>
</head>
<body>
  <p>Foo bar baz</p>
</body>
</html>

The code above is rendered as follows: