Possible Duplicate:
When to use setAttribute vs .attribute= in JavaScript?
Why do you sometimes set an attribute like this:
x.type = "submit";
and other times like this:
x.setAttribute("type", "submit");
I always figured it didn't matter which way, but I'm having an issue doing this:
x.onClick = save;
but when I switch it to this it works:
x.setAttribute("onClick", "save()");
Element.setAttribute() Sets the value of an attribute on the specified element. If the attribute already exists, the value is updated; otherwise a new attribute is added with the specified name and value.
The setAttribute() method is used to set or add an attribute to a particular element and provides a value to it. If the attribute already exists, it only set or changes the value of the attribute. So, we can also use the setAttribute() method to update the existing attribute's value.
The "setAttribute is not a function" error occurs for multiple reasons: calling the setAttribute() method on a value that is not a DOM element. placing the JS script tag above the code that declares the DOM elements. calling the setAttribute method on a jQuery object (should use attr() instead).
Using setAttributeIf the attribute is already assigned to an element, the value is overwritten.
setAttribute
only works on DOM elements and lowercases the attribute name on HTML elements. And you can't use dot notation to assign values to dynamic attribute names.
And there's also this:
Using
setAttribute()
to modify certain attributes, most notably value in XUL, works inconsistently, as the attribute specifies the default value. To access or modify the current values, you should use the properties. For example, useelt.value
instead ofelt.setAttribute('value', val)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With