Home >Web Front-end >JS Tutorial >How Can I Access Object Properties with Special Characters in JavaScript?
Accessing Object Properties with Special Characters
When working with DOM elements, you may encounter situations where the IDs of properties contain special characters, such as periods. Attempting to access these properties using dot notation can result in syntax errors.
Problem:
Consider the following DOM element:
var virDom = document.getElementsByTagName("form")[0];
virDom has two fields with IDs "creditId" and "pwdId..". While you can access "virDom.creditId" without issue, "virDom.pwdId.." will fail due to the periods in the name.
Solution:
To access properties with special characters, you can use bracket notation. This involves enclosing the property name in square brackets:
virDom['creditId'] virDom['pwdId..']
Bracket notation is not limited to DOM elements; it can be used to access properties of any object. It is particularly useful when dealing with characters that are not valid identifiers or when accessing keys that you may not know ahead of time.
The above is the detailed content of How Can I Access Object Properties with Special Characters in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!