-3

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";
ProgramFOX
  • 6,131
  • 11
  • 45
  • 51
shantocv
  • 191
  • 1
  • 3
  • try yourself in browser – rab Jul 18 '13 at 05:04
  • 3
    try it http://jsfiddle.net/arunpjohny/Yr6uq/1/ – Arun P Johny Jul 18 '13 at 05:06
  • 3
    @JaykishanMehta No it shouldn't. `$("myid").innerHTML` wouldn't even work in jQuery. `$("myid")[0].innerHTML` would. – Shawn31313 Jul 18 '13 at 05:06
  • Of course, if you've already loaded jQuery or any other library which reserves '$' as a function name, you'll usually see errors when you redefine it. ;-) – Rob Raisch Jul 18 '13 at 05:07
  • 1
    @FrancisFuerte No it's not a "reserved word". – Dimitar Dimitrov Jul 18 '13 at 05:07
  • @RobRaisch you should be able to override it just fine. If you include jQuery afterwards however, it will override your definition. – mash Jul 18 '13 at 05:07
  • I think the OP doesn't know he's trying to use (and needs to include) jQuery. – Jonathon Reinhart Jul 18 '13 at 05:08
  • @Mash, True, if there is no currently running code which relies on `$`. If you're running Chrome, try opening your JS console and redefine `$` while on this page. *grin* – Rob Raisch Jul 18 '13 at 05:09
  • @RobRaisch works fine. I can't even comment after I do so. :) – mash Jul 18 '13 at 05:10
  • @Mash, well, when I redefine `$` while on this page and then attempt to do anything, even clicking on the page, my console fills up with errors. YMMV. – Rob Raisch Jul 18 '13 at 05:12
  • @RobRaisch well I'm sure there will be errors, as scripts on the page try to call $ in specific ways that it no longer can! But you can still overwrite it. – mash Jul 18 '13 at 05:14
  • For the record, see http://stackoverflow.com/questions/1661197/valid-characters-for-javascript-variable-names if you'd like to name your JS functions like: `function ಠ_ಠ(){return true;}` ;) – Rob Raisch Jul 18 '13 at 05:16

2 Answers2

3

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.

Timothy Jones
  • 21,495
  • 6
  • 60
  • 90
0

Please try this

<div id="myHtml"></div>

$ = function(id) {
  return document.getElementById(id);
}
console.log($("myHtml"));
$("myHtml").innerHTML = "Hello World";
Akbar
  • 91
  • 3