I wanted to make a button with the following JavaScript...
var button = document.createElement('button');
button.type = 'button';
button.appendChild(document.createTextNode('I am button'));
document.body.appendChild(button);
It works great, except in IE7/8 (all I have tested so far).
Message:
Object doesn't support this action
Line:185
Char:9
Code:0
URI:.js
I found a workaround...
document.body.innerHTML = '<button type="button">I am button</button>';
That is, set innerHTML
and let the browser do the parsing.
jsFiddle.
Is there any other way to get this to work in IE without setting the innerHTML
property?
I wanted to make a button with the following JavaScript...
var button = document.createElement('button');
button.type = 'button';
button.appendChild(document.createTextNode('I am button'));
document.body.appendChild(button);
It works great, except in IE7/8 (all I have tested so far).
Message:
Object doesn't support this action
Line:185
Char:9
Code:0
URI:http://example./widget.js
I found a workaround...
document.body.innerHTML = '<button type="button">I am button</button>';
That is, set innerHTML
and let the browser do the parsing.
jsFiddle.
Is there any other way to get this to work in IE without setting the innerHTML
property?
- Does this work: jsfiddle/PHrpz ? (i have no IE) – stewe Commented Aug 30, 2011 at 4:41
- @stewe Nope, it doesn't work in IE 7 or 8 (I used my Chrome IE Extension and it didn't work) – Nathan Commented Aug 30, 2011 at 4:42
-
@Phil I added the error message. It seems IE must know the
type
attribute up front, or it has a problem. – alex Commented Aug 30, 2011 at 4:45 -
@alex Looking at the article in Ray's answer, you could try
setAttribute()
– Phil Commented Aug 30, 2011 at 4:48 -
@Phil I didn't even think to check
setAttribute()
. It appears to work in IE7 + 8. Think it may be time to convert ment to answer :) – alex Commented Aug 30, 2011 at 4:52
3 Answers
Reset to default 6Have you tried .setAttribute()
? The following appears to work in IE 8 (didn't test in 7), Chrome, FF:
<html>
<body>
<script>
var button = document.createElement('button');
button.setAttribute('type','button')
button.appendChild(document.createTextNode('I am button'));
document.body.appendChild(button);
</script>
</body>
</html>
According to this article which you might have seen, the direct createElement
DOM call in IE7/8 does not work with the button
element, but it does work with input
.
You may be right about innerHTML
solutions (and the use of jQuery with HTML source, which is in spirit pretty much the same thing, IMHO) being the only approach.
Very strange about the DOM deficiency in IE7/8. Very interesting find!
Using innerHTML
replaces everything in the element with what you specify.
jQuery .append()
works in IE7/8: (and it is much easier)
$(document).ready(function() {
$('body').append('<button type="button">I am a button</button');
});
Here's a jsFiddle: http://jsfiddle/4ne48/