Home >Web Front-end >JS Tutorial >How to use setAttribute in JavaScript
We often need to dynamically add various attributes to Element in JavaScript. This can be achieved by using setAttribute(), which involves browser compatibility issues.
setAttribute(string name, string value): Add a new attribute with a specified name and value, or set an existing attribute to a specified value.
1. Style issues
In setAttribute("class", value), class refers to changing the attribute "class", so it must be in quotes.
vName represents assigning a value to the style.
For example:
var input = document.createElement("input");
input.setAttribute("type", "text");
input.setAttribute("name", "q");
input.setAttribute("class",bordercss);
When outputting: , that is, the input control has bordercss style attributes
Note: class Properties play an important role in the W3C DOM, but still exist due to browser differences.
Using the setAttribute("class", vName) statement to dynamically set the class attribute of Element works in Firefox, but not in IE. Because the browser using the IE core does not recognize "class", it must use "className" instead;
Similarly, firefox does not recognize "className" either. So the commonly used method is to use both:
element.setAttribute("class", value); //for firefox
element.setAttribute("className", value); //for IE
2. Method Issues such as attributes
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.
But IE does not support it. It is not that IE does not support the setAttribute function, but it does not support using setAttribute to set certain attributes, such as object attributes, collection attributes, and event attributes. In other words, using setAttribute to set style and onclick attributes does not work in IE. It won't work.
In order to achieve compatibility with various browsers, you can use the dot notation method to set the object properties, collection properties and event properties of Element.
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!"); }