spence911 Posted March 23, 2014 Share Posted March 23, 2014 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 elementId. To 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; Link to comment https://forums.phpfreaks.com/topic/287196-how-does-elementid-in-documentgetelementbyidelementid-pass-values-to-a-variable/ Share on other sites More sharing options...
trq Posted March 23, 2014 Share Posted March 23, 2014 elementId is the first argument passed into the setText function. Its a variable. Link to comment https://forums.phpfreaks.com/topic/287196-how-does-elementid-in-documentgetelementbyidelementid-pass-values-to-a-variable/#findComment-1473593 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.