When to use setAttribute vs .attribute= in JavaScript?
You should always use the direct .attribute
form (but see the quirksmode link below) if you want programmatic access in JavaScript. It should handle the different types of attributes (think "onload") correctly.
Use getAttribute
/setAttribute
when you wish to deal with the DOM as it is (e.g. literal text only). Different browsers confuse the two. See Quirks modes: attribute (in)compatibility.
What is happening behind .setAttribute vs .attribute=?
input.value
is dot notation, it sets the value
property of the input object.
It does in no way update any attributes, so trying to get an attribute with the same name will not return the updated value.
If for some reason you have to update the attribute, you would do
input.setAttribute('value', 'new_value');
but you shouldn't have to use that, as you generally should be working with the properties, not the attributes, and you'd set and get the value
property, not the attribute.
An attribute in HTML is a key / value pair inside the opening and closing brackets, as in
<div attribute="attribute_value"></div>
In many cases such attributes will set the initial value of the underlying property, and the property is a named key with a value, that is attached to the internal model of an element, which is what we access with javascript, the object holding the model and data for the element.
Changing any of that objects keys or values does not change the HTML, only the internal representation of the element, the object. However, changing the HTML attributes will in some cases change the object representation of the element.
getAttribute
gets the actual attributes from the HTML, not the properties, while element.value
clearly accesses a named property in the object representing that element.
Why the difference between setting the value of an input via setAttribute or directly?
The main difference between both the approach is setting the underlying defaultValue
property. when you use setAttribute
, the both defaultValue
property as well as the value
property will be updated/set. whereas using .value
will update/set the value
property of it only.
Behavior 1: (setting value using setAttribute)
x.setAttribute("value","test");
x.defaultValue; //"test"
x.value; //"test"
Behavior 2: (setting value directly using value property)
x.value = "test";
x.defaultValue; //""
x.value; //"test"
difference between setAttribute and htmlElement.attribute='value'
difference between setAttribute and htmlElement.attribute='value'
That latter bit, htmlElement.attribute='value'
, isn't quite accurate. You're not setting an attribute there, you're setting a property.
DOM element instances in memory have various properties, some of which connect to or relate to attributes and others which don't.
Attributes, on the other hand, are name/value pairs that are read directy from the HTML markup (and if you serialize a DOM element, for instance by accessing its innerHTML
property, are written to the markup you get back).
When the property and attribute are related/linked in some way, the property is called a reflected property (of the attribute). Sometimes, the reflected property's name isn't quite the same as the attribute's name (class
becomes className
, for
becomes htmlFor
), and sometimes the link between them isn't 1:1.
So for instance, id
is a reflected property of the id
attribute. But select boxes have a selectedIndex
property for which there's no attribute.
do both of them will do exactly the same task ?
and will they be different in some situations ?
It depends on the attribute/property:
id
and several others are directly reflected: Setting theid
property and setting theid
attribute do exactly the same thing. Offhand, this is also true of thehtmlFor
property /for
attribute (except on old IE which has bugs insetAttribute
there), therel
property/attribute, theclassName
/class
attribute (except on old IE which has bugs insetAttribute
there), thename
attribute on form fields and some other elements, themethod
andaction
properties/attributes on forms, and several others.The
value
property, on the other hand, doesn't set thevalue
attribute at all. It just gets its default value from it. On most browsers ("all" at this point?), there's a separatedefaultValue
property which does directly reflect thevalue
attribute.The
href
property is slightly different from thehref
attribute in relation to relative vs. absolute links. The attribute can contain a relative path, and usingstr = elm.getAttribute("href")
gives you that relative path; if you read the property (str = elm.href
), it will always be an absolute path (e.g., the resolved path). Setting thehref
property to a relative path sets the attribute to that path, but again reading tehhref
property will give you the absolute (resolved) version. Setting thehref
property to an absolute path will set the attribute to that absolute path.There are several boolean properties which are represented as booleans (true/false), but since attribute values are always strings, the attribute is either not there for false (
getAttribute
returnsnull
) or there for true. If it's there, it must have the value""
or the same as its name (e.g.,multiple="multiple"
, case-insensitive), although in practice browsers treat any present attribute astrue
regardless of its actual content.Several properties aren't reflected in attributes at all, so setting them doesn't set/change any attribute.
is one of them more efficient than the other ?
It's never going to make a big enough difference to care, so it doesn't matter. It also probably varies dramatically by browser.
What is the difference between setAttribute and dot notation in Javascript?
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 of
elt.setAttribute('value', val)
.
Difference between setAttribute and setAttributeNS(null,
setAttribute() is a DOM 1 function. setAttributeNS() is a DOM 2 function that resolves the problem of conflicting tag or attribute names by specifying the xmlns namespace that should apply to the tag/attribute in the first argument.
If an attribute does not have a defined namespace prefix, the first argument must be null. You could use setAttribute() but for consistency it is advisable to stick to setAttributeNS(). See:
https://developer.mozilla.org/en/docs/Web/SVG/Namespaces_Crash_Course#Scripting_in_namespaced_XML
"However, note carefully: the Namespaces in XML 1.1 recommendation
states that the namespace name for attributes without a prefix does
not have a value. In other words, although the attributes belong to
the namespace of the tag, you do not use the tag's namespace name.
Instead, you must use null as the namespace name for unqualified
(prefixless) attributes."
Related Topics
How to Check If a Checkbox Is Checked
Differencebetween 'New Object()' and Object Literal Notation
How to Output an Iso 8601 Formatted String in JavaScript
Node.Js Plans to Support Import/Export Es6 (Ecmascript 2015) Modules
How to Get Unique Values in an Array
Define Global Variable with Webpack
Binding Arrow Keys in Js/Jquery
How to Gain Access to the Closure of a Function
Are JavaScript Arrays Primitives? Strings? Objects
Babel File Is Copied Without Being Transformed
How to Determine User's Locale Within Browser
JavaScript % (Modulo) Gives a Negative Result for Negative Numbers
Empty Arrays Seem to Equal True and False at the Same Time
How to Get the Non-Enumerable Inherited Property Names of an Object