Jump to content

How does elementId in document.getElementById(elementId) pass values to a variable?


spence911

Recommended Posts

Hello mates, I'm a newbie to JavaScript. Normally when I assign an HTML element to a variable created in JavaScript I place the element id in quotes like this:

var output = document.getElementById('output');

But there is something new that I've come across:

var output = document.getElementById(elementId);

elementId is an undeclared parameter and it is without quotes. 'output' in the first snippet refers to <p id="output"></p> in the HTML code. What is surprising to me is that var output = document.getElementById(elementId); works just the same even though there is no HTML element declared with the name elementIdTo put this into context, the code is in 2 files; today.html and today.js.

 

today.html:

<html>
<head>
<title>Today</title>
</head>
<body>
<p id="output"></p>
<script src="today.js"></script>
</body>
</html>

today.js:

function setText(elementId, message) {
    'use strict';
    
    if ( (typeof elementId == 'string')
    && (typeof message == 'string') ) {
    
        // Get a reference to the paragraph:
        var output = document.getElementById(elementId);
    
        // Update the innerText or textContent property of the paragraph:
		if (output.textContent !== undefined) {
			output.textContent = message;
		} else {
			output.innerText = message;
		}
    
    } // End of main IF.

}
function init() {
    'use strict';
    var today = new Date();
    var message = 'Right now it is ' + today.toLocaleDateString();
    message += ' at ' + today.getHours() + ':' + today.getMinutes();

    // Update the page:
    setText('output', message);
    
} // End of init() function.
window.onload = init;

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.