简体   繁体   中英

How can I access object properties containing special characters?

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?

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.

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"])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM