Reputation: 6499
I'm just starting out with JS and I was wondering how it's possible to show the outcomes of my code?
Here is a small peice of test code I want to use but when viewed in a browser the page is blank:
if ( 11 > 10 )
{
console.log("You made it!")
}
else
{
console.log("You have just died!")
}
I was wondering how it's possible to render my code the same way this website does:
http://repl.it/languages/JavaScript
Upvotes: 0
Views: 971
Reputation: 5993
The quick and dirty way is to do this instead:
document.write( "text" ) //de ...or:
document.writeln( "text" )
The more elegant way is to create a DOM element and to write into that, for example:
Create an element like <div id="console"></div>
in your HTML ( or do this with JS also ), then:
function debug_output( text ) {
document.getElementById( "#console" )
.insertAdjacentHTML(
'beforeend',
'<span class="debug_output">' + text + '</span><br/>'
);
//de thanks to @cookiemonster for the .appendChild fix
}
Since you say you want pure text in the browser, I am first showing you how not to use console.log
but to write directly to the browser.
Again, you will want to write into into the DOM. The second example I gave lets you do that, and perhaps style or place your debug output.
Completed solution, with the above "more elegant" way:
if ( 11 > 10 ) {
debug_output("You made it!")
} else {
debug_output("You have just died!")
}
Upvotes: 2
Reputation: 6349
If you can wrap you code into particular function then you can append your javascript code inside the pre
tag, and finally into body, something like this.
var myJsCode = function () {
if ( 11 > 10 ) {
console.log("You made it!")
}
else {
console.log("You have just died!")
}
}
document.write('<pre>' + myJsCode + '</pre>');
Upvotes: -2
Reputation: 4906
You're printing some values to the console; thus you need to use the developer tools installed on the browser of your preference.
For example https://developers.google.com/chrome-developer-tools/
If you want to show the content within the html itself, then you need to insert a DOM element into your document.
var container = document.getElementById('container');
if ( 11 > 10 )
{
container.innerHTML ="You made it!";
}
else
{
container.innerHTML = "You have just died!";
}
Upvotes: 1
Reputation: 477
Depends what you're trying to do... you could alert the user
alert(MESSAGE);
Or you could set the value of a DIV:
document.getElementById('someDiv').innerHTML = MESSAGE;
More examples here:
Print value returned by a function to screen in javascript
Upvotes: 0