-5
<!DOCTYPE html>
<html>
<head>
<title>LearnJS</title>
</head>
<body>
    <script>
            console.log('hello World\nThis is me');
            alert("This is an \nalert.");
    </script>
</body>
</html>

I have tried this code and run in TORCH borwser... The only output shown is alert But it doesn't display output of console.log... What is the possible solution... I have use

document.write('hello World\nThis is me');

But this code doesn't feed new line so i was supposed to use console.log...

2 Answers2

0

It is working fine here :). Run Code Snippet

<!DOCTYPE html>
<html>
<head>
<title>LearnJS</title>
</head>
<body>
    <script>
            console.log('hello World\nThis is me on console');
            alert("This is an \nalert.");
            document.write("This is an document.write.");
    </script>
</body>
</html>

Note:

  • developers use console.log() for logging useful information on browser console
  • document.write() modifies what user sees in the browser by adding additional content to DOM.
  • alert()'s are used to alert end users who access the web page on browser.

N.B If you're in confusion about How stackoverflow.com shows console.log() on a browser div. Then see here https://stackoverflow.com/a/20256785/1138192 it is kind of overriding the default behavior of console.log() to show the messages on browser div. Hope this helps :)

A l w a y s S u n n y
  • 36,497
  • 8
  • 60
  • 103
  • Might want to mention why the console.log message shows up on the snippet page here as OP seems to be under the impression console.log would write to the page itself natively. – Patrick Evans Sep 17 '18 at 02:40
0

console.log() only displays in the developer console of the browser. It does not display on the web page itself.

Your code is not feeding a new line because \n only shows in the source code not on the page. To display a new line in HTML on the page you need to use a <br> tag or use other form of spacing.

So, instead of:

document.write('hello World\nThis is me');

You could use:

document.write('hello World<br>This is me');

However, rather than using document.write(), you may prefer to write to a specific element in the page. Below I give an element an id of data and then use the JavaScript code to write to this element.

<!DOCTYPE html>
<html>
<body>
<div id="data">You can put text here or leave it blank. It will be replaced.</div>
<script>
document.getElementById("data").innerHTML = "Hello world<br>This is me";
</script>
</body>
</html>

Notice also, I need to place the document.getElementByID("data") script after the div is created. If I place it before it will not be able to find it. The script code is therefore placed at the end of the <body> section. There are better ways to do this (such as placing JavaScript code in an external file and using defer), but for your purposes this should work quite well.

kojow7
  • 10,308
  • 17
  • 80
  • 135