Why does appendChild only work when I remove the d

2019-08-20 20:39发布

When I put any sort of doctype declaration like <!DOCTYPE html >, appendChild does not work.... Why?

<form>
<script language="javascript">
    function function2() {
        var myElement = document.createElement('<div style="width:600; height:200;background-color:blue;">www.java2s.com</div>');
        document.forms[0].appendChild(myElement);
    } 
</script>


<button onclick="function2();"></button>

</form>

I'm trying to get data from a popup window's parent opener...is that possible? The data can be a string literal or value tied to the DOM using jQuery .data()

1条回答
Juvenile、少年°
2楼-- · 2019-08-20 20:56

If you're having this problem in IE, it's probably because the presence of a DOCTYPE declaration forces the browser into "standards-compliance" mode. This can cause code that doesn't conform to expected standards to break.

In your case, it's probably because document.createElement doesn't accept an HTML fragment - it accepts an element name, e.g. document.createElement('div').

Try replacing your function body with something like this:

var myElement = document.createElement('div');
myElement.style.width = '600px';
myElement.style.height = '200px';
myElement.style.backgroundColor = 'blue';
myElement.appendChild(document.createTextNode('www.java2s.com'));
document.forms[0].appendChild(myElement);

Read up on the document object model here: https://developer.mozilla.org/en/DOM

Also, jQuery is good for easily creating elements using the syntax you specified.

查看更多
登录 后发表回答