We often need to add various properties to the element dynamically in JavaScript, which can be achieved by using setattribute (), which involves browser compatibility issues
SetAttribute (string name, String value): Adds a new property that specifies the name and value, or sets an existing property to the specified value.
1, Style problems
The class in setattribute ("Class", value) refers to changing the attribute of "class" so that it is quoted.
VName represents the assignment of a style.
For example:
Copy Code code as follows:
var input = document.createelement ("input");
input.setattribute ("type", "text");
Input.setattribute ("name", "Q");
Input.setattribute ("Class", bordercss);
Output: <input type= "text" name= "Q" class= "Bordercss", that is, the input control has BORDERCSS style properties
Note: The class attribute plays an important role in the Web-consortium DOM, but it still exists because of browser variability.
Dynamically setting the class attribute of an element using setattribute ("Class", VName) statement is a good way to do it in Firefox, but not in IE. Because the browser using IE kernel does not know "class", to switch to "className";
Also, Firefox does not know "className". So the common method is both:
Copy Code code as follows:
Element.setattribute ("Class", value); For Firefox
Element.setattribute ("ClassName", value); For IE
2, method attributes and other issues
For example:
Copy Code code as follows:
var bar = document.getElementById ("TESTBT");
Bar.setattribute ("onclick", "Javascript:alert (' is a test! ');");
Here, using setattribute to specify the onclick properties of E, simple, very good understanding.
However, IE does not support, IE does not support setattribute this function, but does not support the use of setattribute set some properties, such as Object properties, collection properties, event properties, In other words, using setattribute to set style and onclick properties is not feasible in IE.
To achieve compatibility with various browsers, you can set the element's object properties, collection properties, and event properties by using the dot notation method.
Copy Code code as follows:
document.getElementById ("TESTBT"). ClassName = "Bordercss";
document.getElementById ("TESTBT"). Style.csstext = "color: #00f;";
document.getElementById ("TESTBT"). Style.color = "#00f";
document.getElementById ("TESTBT"). onclick= function () {alert ("This is a test!");}