views:

36

answers:

1

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  A: 

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.

harto
`myElement.style` is an object with individual properties for each CSS property, not a string. Assigning each property in turn will work in all browsers: `myElement.style.width = "600px"; myElement.style.height = "200px"; myElement.style.backgroundColor = "blue";`
Tim Down
ah yeah, thanks - updated.
harto