The setattribute () function can set the properties of an object, and if this property does not exist, this property is created.
Syntax structure:
El.setattribute (Name,value)
Parameter list:
Parameter description
Name required. Specify the name of the property to set.
Value required. Specify the property value to set.
Code instance:
The above code can reset the div's ID property value and pop up the new set's id attribute value.
Example two:
The above code can set the div's Newattr property value and eject this property value. It is important to note here that because the DIV does not have the Newattr attribute by default, this time the setattribute () function first creates this property and then assigns it a value.
The above two code instances can be successfully executed in all major browsers, but this does not mean that the setattribute () function can be compatible with each browser.
Take a second look at the code example:
The above code, in the standard browser can set the font size to 18px, font color set to red, but in the IE6 and IE7 browser does not take effect.
However, you can still get the property value "TextColor" Using Mydiv.getattribute ("class").
That is, the setattribute () function can be used in IE6 or IE7 browsers, but it is not valid for all properties.
Here's a list of attributes that have the above problems:
1.class
2.for
3.cellspacing
4.cellpadding
5.tabindex
6.readonly
7.maxlength
8.rowspan
9.colspan
10.usemap
11.frameborder
12.contenteditable
13.style
In order to solve the above problems, write a common cross browser interface method for setting element properties:
Dom= (function () {
var fixattr={
tabindex: ' TabIndex ',
readonly: ' readonly ',
' for ': ' htmlfor ',
' Class ': ' ClassName ',
maxlength: ' maxlength ',
cellspacing: ' cellspacing ',
cellpadding: ' cellpadding ',
rowspan: ' rowspan ',
colspan: ' colspan ',
usemap: ' Usemap ',
frameborder: ' frameborder
', Contenteditable: ' contenteditable '
},
div=document.createelement (' div ');
Div.setattribute (' class ', ' t ');
var supportsetattr = Div.classname = = ' t ';
return {
setattr:function (el, name, Val) {
el.setattribute (supportsetattr? Name: (fixattr[name) | | name), VAL
},
getattr:function (el, name) {return
el.getattribute (supportsetattr? Name: (fixattr[name) | | name ));
}
}
}) ();
First, the standard browser uses the original property name directly, and secondly, IE6/7 attributes that are not listed above still use the original property name, and finally these special properties use FIXATTR, such as class.
The code instance above can be modified to the following form:
The above code is available in all major browsers, and you can set the font size to 18px and the color set to red.
The Style property can be compatible using the form el.style.color= "XXX".
The above mentioned is the entire content of this article, I hope you can enjoy.