Jump to content

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

Go to solution Solved by trq,

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.



<p id="output"></p>
<script src="today.js"></script>


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;
Link to comment
Share on other sites

This thread is more than a year old. Are you sure you have something important to add to it?

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • 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.