开发者

Is using `innerHTML` the only way to create a `button` element in JavaScript with the `type` attribute?

开发者 https://www.devze.com 2023-03-31 11:29 出处:网络
I wanted to make a button with the following JavaScript... var button = document.createElement(\'button\');

I wanted to make a button with the following JavaScript...

var button = document.createElement('button');
button.type = 'button';
button.appendChild(document.createTextNode('开发者_JAVA技巧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.com/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?


Have 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.net/4ne48/

0

精彩评论

暂无评论...
验证码 换一张
取 消