javascripthtmlbooleansetattributegetattribute

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


Solution

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