Growler Growler - 1 year ago 60
HTML Question

set/getAttribute comparisons only work with strings?

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 comparing against bools work?

FIDDLE

Answer Source

This 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 ("")

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download