I would like to set a span
node's visited
attribute to true
or false
based on if it has been visited.
test();
function test () {
var el = document.createElement("span");
el.setAttribute("visited", false);
el.setAttribute("visited", true);
alert(el.getAttribute("visited") === true); //False
alert(el.getAttribute("visited") === "true"); //True
}
I initially set the attribute "visited" to boolean false, then set the boolean to true. I noticed that when I checked if the attribute was true
, it returned false, but if I checked the string true
, it returned true.
The MSN Docs only talk about the attributeName as needing to be string, not the value. So why doesn't paring against bools work?
FIDDLE
I would like to set a span
node's visited
attribute to true
or false
based on if it has been visited.
test();
function test () {
var el = document.createElement("span");
el.setAttribute("visited", false);
el.setAttribute("visited", true);
alert(el.getAttribute("visited") === true); //False
alert(el.getAttribute("visited") === "true"); //True
}
I initially set the attribute "visited" to boolean false, then set the boolean to true. I noticed that when I checked if the attribute was true
, it returned false, but if I checked the string true
, it returned true.
The MSN Docs only talk about the attributeName as needing to be string, not the value. So why doesn't paring against bools work?
FIDDLE
Share edited Mar 4, 2015 at 20:32 sfletche 49.8k31 gold badges108 silver badges120 bronze badges asked Mar 4, 2015 at 20:03 user3871user3871 12.7k36 gold badges140 silver badges282 bronze badges 2-
7
Yes,
attributes
are always strings, butproperties
can be several different types. – KJ Price Commented Mar 4, 2015 at 20:04 - MSDN isn't a normative reference for the relevant standard, the W3C is: setAttribute, getAttribute. – RobG Commented Mar 4, 2015 at 20:37
3 Answers
Reset to default 8This is because getAttribute
return type is string
not bool
Return Value: A String, representing the specified attribute's value.
Note: If the attribute does not exist, the return value is null or an empty string ("")
The ===
operator checks both value and type (with no implicit coercion of types).
Since getAttribute
returns a string value, the parison is only true
when pared to the string "true" and not when pared to the boolean value of true
.
To put it another way, when using the ===
operator...
true === 'true' // false
'true' === 'true' // true
true === true // true
Here is the definition of attributes as defined by the HTML standard:
3.2.3.1 Attributes
Except where otherwise specified, attributes on HTML elements may have any string value, including the empty string. Except where explicitly stated, there is no restriction on what text can be specified in such attributes.
So, to repeat what was already stated, HTML attributes are always strings.