-1

In JavaScript, is there a difference between

elem['textContent'] = "Test";

and

elem.textContent = "Test";

when elem is a HTMLElement?

Cristi Pufu
  • 9,002
  • 3
  • 37
  • 43
HischT
  • 933
  • 1
  • 9
  • 26
  • `elem.['textContent']` is invalid syntax, I guess you mean `elem['textContent']` (no dot). If this is the case, the two are functionally identical. – Nikos Paraskevopoulos Mar 07 '14 at 12:27
  • @CristiPufu I'm not sure if silently removing the syntax error is a good thing to do while editing questions. It might be there because it's really in the OPs code and thus should be discussed. – Yoshi Mar 07 '14 at 12:28
  • 2
    you should read this: http://stackoverflow.com/questions/4968406/javascript-property-access-dot-notation-vs-brackets – Cristi Pufu Mar 07 '14 at 12:29

1 Answers1

3

They do the same. They set the property on the object (it can be any type of object, so it does not make a difference whether it is an HTMLElement, Function or any other object).

The only difference is that you can pass an expression into the bracket notation, while the other form only allows names that qualify as an identifier.

For example:

elem['text' + 'Content'] = "Test"; //works

var t = ['textContent'];
elem[t[0]] = "Test"; //works

elem[(function () { return 'textContent'; })()] = "Test"; //works
kapa
  • 77,694
  • 21
  • 158
  • 175