SoFunction
Updated on 2025-04-09

Access to DOM element attributes that require special processing

Copy the codeThe code is as follows:

var props = {
'for' : 'htmlFor',
'class': 'className',
readonly: 'readOnly',
maxlength: 'maxLength',
cellspacing: 'cellSpacing',
rowspan: 'rowSpan',
colspan: 'colSpan',
tabindex: 'tabIndex',
usemap: 'useMap',
frameborder: 'frameBorder'
}

To put it a little off topic, if you use json format to create objects, it is recommended that the attributes do not require single or double quotes, unless some ecmascript keywords, such as 'for', 'class' above, etc., it is recommended to use them normally.
Single quotes do not mean that single quotes are definitely better than double quotes and are more in line with the specifications, but a habit is still very important. Don’t have single quotes and double quotes in the code.
Let's give a simple example:
Copy the codeThe code is as follows:

<label for="username" >name:</label><BR><input type="text" name="username"/><BR>

If you want to obtain a certain attribute value of a DOM element directly through this access method, you must make a simple change for the above attribute access.

For example in the above example, you want to get the for attribute value of label.
Copy the codeThe code is as follows:

var ele = ('test');
var val = ;
//or
val = ele['htmlFor'];
//If accessed through standard DOM methods, no special processing is required
val = ('for');
val = ('for').value;

Similarly, for class, readonly, etc., the above access methods are also suitable.

I personally think that accessing directly through attributes may be faster than accessing through DOM methods.
The following article will introduce the access to special attributes.