We often need to dynamically add various attributes to the Element in JavaScript, which can be achieved by using setAttribute (), which involves the browser compatibility problem setAttribute (string name, string value ): add a new attribute with the specified name and value, or set an existing attribute to the specified value.
1. style issues
In setAttribute ("class", value), class is used to change the attribute "class", so it must be enclosed by quotation marks.
VName indicates that the style is assigned a value.
For example:
The Code is as follows:
Var input = document. createElement ("input ");
Input. setAttribute ("type", "text ");
Input. setAttribute ("name", "q ");
Input. setAttribute ("class", bordercss );
Output: That is, the input control has the bordercss style attribute.
Note: The class Attribute plays an important role in W3C DOM, but it still exists due to browser differences.
The setAttribute ("class", vName) statement is used to dynamically set the class attribute of an Element in firefox, but not in IE. Because the browser using the IE kernel does not know "class", you should use "className" instead ";
Similarly, firefox does not know "className ". Therefore, the common methods are both:
The Code is as follows:
Element. setAttribute ("class", value); // for firefox
Element. setAttribute ("className", value); // for IE
2. Method attributes and other issues
For example:
The Code is as follows:
Var bar = document. getElementById ("testbt ");
Bar. setAttribute ("onclick", "javascript: alert ('this is a test! ');");
Here, setAttribute is used to specify the onclick attribute of e, which is simple and easy to understand.
However, IE does not support the setAttribute function, but does not support setting certain attributes with setAttribute, such as object attributes, set attributes, and event attributes, that is to say, setting style and onclick attributes with setAttribute does not work in IE.
To achieve compatibility with various browsers, you can use the dot symbol method to set object attributes, set attributes, and event attributes of the Element.
The Code is as follows:
Document. getElementById ("testbt"). className = "bordercss ";
Document. getElementById ("testbt" ).style.css Text = "color: # 00f ;";
Document. getElementById ("testbt"). style. color = "# 00f ";
Document. getElementById ("testbt"). onclick = function () {alert ("This is a test! ");}