We often need to dynamically add various attributes to the Element in JavaScript, which can be achieved by using setAttribute (), which involves the compatibility of the browser. SetAttribute (stringname, stringvalue): Add a new attribute with the specified name and value, or... SyntaxHi
We often need to dynamically add various attributes to the Element in JavaScript, which can be achieved by using setAttribute (), which involves the compatibility of the browser.
SetAttribute (string name, string value): adds a new attribute with the specified name and value, or sets an existing attribute as 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:
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:
Element. setAttribute ("class", value); // for firefox
Element. setAttribute ("className", value); // for IE
2. Method attributes and other issues
For example:
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.
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! ");}