38

I have a form DOM element:

var virDom = document.getElementsByTagName("form")[0];

virDom has two fields with IDs creditId and pwdId... I can access virDom.creditId without any issue, but virDom.pwdId.. is failing with a syntax error, because of the periods contained in the name.

How can I access such properties?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
user1673257
  • 501
  • 1
  • 4
  • 5

2 Answers2

62

Use bracket notation:

virDom['creditId']
virDom['pwdId..']

This applies to any object, and it is particularly useful for non-identifier-safe characters and also for accessing keys that you may not know ahead of time.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
2

For a nested object with a special character like below,

var details = {"name-details": {"first-name": "Kiran"}}

use

console.log(details["name-details"]["first-name"])
Kiran Poojary
  • 163
  • 2
  • 6