Reputation: 62
Im doing an incredibly basic javascript exercise for school practicing for Objects. I thought the normal document.write would work but it doesn't, ive looked many places but a lot of it is just for the console. The error is
Failed to execute 'write' on 'Document': It isn't possible to write into a document from an asynchronously-loaded external script unless it is explicitly opened.
If anyone can help that would be great, sorry if its really easy
Here is my code
var oPerson = {
firstName: 'John',
lastName: 'Travis',
gender: 'Male',
age: 22,
district: 'Northshore',
hairColor: 'Brown',
hairLength: 'Short',
height: '6\'11"',
weight: '74kg',
martialStatus: 'Engaged'
}
document.write(oPerson);
document.write(oPerson.district);
oPerson.resident = "yes";
document.write(oPerson);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Exercise - Personal Info</title>
<script src="practice9JS.js" type="text/javascript"></script>
</head>
<body>
</body>
</html>
Upvotes: 0
Views: 2835
Reputation: 236
I'm not sure what you try to do, but if simply post content of object without any formatting, this could work for you.
var oPerson = {
firstName: 'John',
lastName: 'Travis',
gender: 'Male',
age: 22,
district: 'Northshore',
hairColor: 'Brown',
hairLength: 'Short',
height: '6\'11"',
weight: '74kg',
martialStatus: 'Engaged'
}
var app = document.getElementById('app');
app.innerHTML = JSON.stringify(oPerson);
<div id="app">
</div>
Upvotes: 0
Reputation: 683
It's not advised to use document.write
, becasue it have to be executed before loading the page. Also it's executed in HTML place exactly where was added. So in case of your code it will be added to head
of the page, not the body.
If you wish to just add something to HTML, you can do it with
document.appendChild`. Where you create new element, provide some necessary info and append it to the body.
e.g. https://codepen.io/msamsel/pen/zEMZXX?editors=1010
function printToBody( str ) {
var par = document.createElement( 'p' );
par.innerText = str;
document.getElementsByTagName( 'body' )[0].appendChild( par );
}
var oPerson = {
firstName: 'John',
lastName: 'Travis',
age: 22
}
printToBody( oPerson.firstName )
printToBody( oPerson.lastName )
printToBody( oPerson.age )
If you really want to use document write, then move script from head to body. Then document.write
should execute there.
Upvotes: 0
Reputation: 36
Your document.write() calls are exectuting as the HTML is being read. By the time the DOM loads, your messages are no longer visible. Try this:
setTimeout(() => document.write(oPerson.lastName), 1000);
Upvotes: 1