Use function in multiple divs?

If I have four div’s with id 1,2,3,4 and I want this function to write “good morning” in each div.
My code below does not work.
Does anyone know?

function beCheerful(x) {
	let line = "";
	var box = document.getElementById(x);
	line +=('good morning ');
	box.innerHTML = line;
}
		
for(x = 1; x <=4; x++){
   beCheerful(x);
}

The posted code works for me. Therefore, the problem is elsewhere, such as in the order of the code on the page or some other error in the markup/javascript. Have you checked the browser’s develop tools console tab?

Ok, thanks! I got it to work.
But only with the code on the same page.
How can I get it to work it in a separat .js file?

Move your javascript to a separate file, usually named with a .js extension - eg hellodivs.js.

Then you can use the <script> tag to include that file in your page:

<script src="hellodivs.js"></script>

The <script> tag won’t show any content in the browser; it’s just a signal to load the associated javascript. It’s usually best to add the <script> tag just before the closing </body> tag, to ensure the browser knows you html structure before it tries to run your code against it.

That’s what I tried from the beginning, but it doesent work from separat file!

Could you show us the contents of your HTML and JS file?

Sponsor our Newsletter | Privacy Policy | Terms of Service