HTML file
<div id="myid"></div>
Are these codes possible or not valid in JavaScript?
1.
function $(id) {
return document.getElementById(id);
}
2.
$("myid").innerHTML = "hello world";
HTML file
<div id="myid"></div>
Are these codes possible or not valid in JavaScript?
1.
function $(id) {
return document.getElementById(id);
}
2.
$("myid").innerHTML = "hello world";
below codes are possible or not in javascript ?
The answer to this is yes, that code is fine.
There is nothing wrong with your code that you've shown. As many commenters have pointed out, it works fine in a JS fiddle.
$
is not, as one commenter said, a reserved word, see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Reserved_Words
However, I would recommend against using $
if this code is to be used by others. $
is often used as the shortcut to jQuery, which is what is confusing some commenters. I believe (for readability) you would be better off using a different single character.
Please try this
<div id="myHtml"></div>
$ = function(id) {
return document.getElementById(id);
}
console.log($("myHtml"));
$("myHtml").innerHTML = "Hello World";