-3

I can try to get my Javascript output. if I write only 1 function I can, But if I would write 2 or more function, how I can get output of function which I want?

JS File:

var time = new Date();
var currenthour = time.getHours();
var welcome;

if(currenthour<=12)
welcome = 'Good Morning';
else if(currenthour >=12 && currenthour <= 17)
welcome = 'Good Afternoon';
else if(currenthour >= 17 && currenthour <= 24)
welcome = 'Good Evening';
document.write(welcome);

HTML File

<!DOCTYPE html>
<html>
<head>
<title>WinMachines</title>
<link rel = "shortcut icon" type= "image/png" href="images\logo.png">
<link rel = "stylesheet" type ="text/css" href= "css/style.css">

</head>
<body background="images/lg.jpg">
<h2></h2>

<script src="js/main.js"></script>
</body>
</html>
  • 1
    [javascript - What are alternatives to document.write? - Stack Overflow](https://stackoverflow.com/questions/4537963/what-are-alternatives-to-document-write) – user202729 Jan 29 '21 at 15:15
  • (that having said, if you just want to see the output, just `console.log` is t. Or use Node.js.) – user202729 Jan 29 '21 at 15:15
  • @user202729 at html file?) I want to get outpur at html file, and I have written to or more function at js file. How I can choose output which I want – Hacveddin Jan 29 '21 at 15:17
  • You don't get output "at HTML file". You want the output on the document. Read that link. `document.write` is very likely to be the problem here. – user202729 Jan 29 '21 at 15:18
  • I want to see output on HTML file, but how I dont know – Hacveddin Jan 29 '21 at 15:19
  • Read the linked question and answers there. – user202729 Jan 29 '21 at 15:20
  • Is your question answered? If yes, please mark the correct answer. If not, please comment accordingly. – connexo Apr 14 '21 at 09:37

2 Answers2

0

If you have multiple functions in your JS file and you want to call a specific one you should be able to do so by calling that function out in another set of <script> tags:

<script src="js/main.js" type="text/javascript"></script>
<script>
    function_1();
</script>
<script>
    function_2();
</script>

etc. I've done this before and it has worked for me.

Darren Woodson
  • 68
  • 1
  • 11
0

Don't use document.write for modifying existing elements. Instead use DOM element selector methods like document.getElementById (if the element has a unique id), or the more modern document.querySelector(cssSelectorString) which will return the first match in the document.

const time = new Date();
const currenthour = time.getHours();
let welcome;

if (currenthour <= 12)
  welcome = 'Good Morning';
else if (currenthour >= 12 && currenthour <= 17)
  welcome = 'Good Afternoon';
else if (currenthour >= 17 && currenthour <= 24)
  welcome = 'Good Evening';
  
document.querySelector('h2').textContent = welcome;
<h2></h2>
connexo
  • 53,704
  • 14
  • 91
  • 128