search

Home  >  Q&A  >  body text

How to access object properties with special characters?

<p>I have a <code>form</code> DOM element: </p> <pre class="brush:php;toolbar:false;">var virDom = document.getElementsByTagName("form")[0];</pre> <p><code>virDom</code> has two fields with IDs, namely <code>creditId</code> and <code>pwdId..</code>. I can access <code>virDom.creditId</code> without issue, but <code>virDom.pwdId..</code> causes a syntax error due to a period in the name. </p> <p>How do I access a property like this? </p>
P粉463824410P粉463824410464 days ago500

reply all(1)I'll reply

  • P粉514001887

    P粉5140018872023-08-23 16:10:38

    Use square bracket notation:

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

    This works for any object and is particularly useful for non-identifier safe characters and for accessing keys that may not be known in advance.

    reply
    0
  • Cancelreply