I wanted to assign a link tag to innerHTML of a HTML control. But this is not working properly in Internet Explorer. However when I try to assign anything other than <link>
& <style>
tags it works fine.
<html>
<head>
<script type="text/javascript">
function getValue()
{
var x=document.getElementById("myHeader");
x.innerHTML='<link \"http://test.com/css/template.css\" rel=\"stylesheet\"><div>abc</div>';
alert(x.innerHTML);
}
</script>
</head>
<body>
<h1 id="myHeader" onclick="getValue()">Click me!</h1>
</body>
</html>
Also, If I change sequence of <div>
tag and <link>
tag above it works fine in Internet Explorer also.
x.innerHTML='<div>abc</div><link \"http://test.com/css/template.css\" rel=\"stylesheet\">';
Please suggest! Thanks.
EDIT: This is a bug in Internet Explorer with ExtJs. More information at
http://www.sencha.com/forum/showthread.php?30110-internet-explorer-autoLoad-css-not-applied
The use of innerHTML creates a potential security risk for your website. Malicious users can use cross-site scripting (XSS) to add malicious client-side scripts that steal private user information stored in session cookies.
Disadvantages of innerHTMLIt is very slow because as inner HTML already parses the content even we have to parse the content again so that's why it takes time. When we have used the event handlers then the event handlers are not automatically attached to the new elements created by innerHTML.
innerHTML is slow because it has to look for HTML tags in the value, and parse it into DOM nodes. If you're just inserting plain text that doesn't contain any HTML tags, use textContent instead.
dangerouslySetInnerHTML is an attribute under DOM elements in React. According to the official documentation, dangerouslySetInnerHTML is React's replacement for using innerHTML in the browser DOM.
innerHTML won't work in IE, but using DOM methods it will:
function getValue()
{
var x=document.getElementById("myHeader")
, link = document.createElement('link')
, div = document.createElement('div');
x.innerHTML = '';
x.appendChild(link);
x.appendChild(div);
div.innerHTML = 'abc';
link.href = 'http://test.com/css/template.css';
link.rel = 'stylesheet';
alert(x.innerHTML);
}
Although the reference states a link
tag may only appear in the header, interesting enough the style link does work if you use the code I provided, in all browsers I tried (IE, firefox, chrome). See this jsfiddle (where I used a real css-href from test.com ;-)
If you however want to place the link
in it's rightful section (<head>
), use:
var header = document.getElementsByTagName('head')[0];
, link = document.createElement('link');
header.appendChild(link);
link.href = 'http://test.com/css/template.css';
link.rel = 'stylesheet';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With