So I was advised recently not to use document.write. But I can’t seem to figure out how to use DOM manipulation to make it document print on screen. This function works so that you hit the button enter the number of miles traveled by car and you get your carbon foot print. Only with document.write it overwrites the entire page after you click the button. I tried getElementbyId but it doesn’t seem to print anything so I know I’m probably not using it correctly. Any ideas on an alternative that will complete the function without overwriting the page would be much helpful>
Below is the code I have with just document.write, the one that overwrites the entire page:
<script>
$(document).ready(function() {
$(".button").click(function() {
var myNumber = 19.2;
var myAnswer = prompt ("How many miles did you travel?");
document.write( " Your Carbon Foot print is:" + myAnswer * myNumber + "lbs" );
});
});
</script>
DOM manipulation involves creating document elements and inserting them into the document tree. It’s something that should become second nature to you if you want to do extensive work with JS:
You probably want to append the text to something else, but the above should have a similar affect and not overwrite the entire page.