Search code examples
jqueryattributesjquery-attributes

Why does jQuery always return 'open' for $.attr('open'), regardless of the actual value of the attribute?


In jQuery, why does this:

$('<div open="whatever">').attr('open')

Always evaluate to 'open' instead of 'whatever'? In contrast, this:

$('<div asdf="whatever">').attr('asdf')

Evaluates to 'whatever' as expected.

Yes, I am aware that open and asdf are not valid HTML attributes; I'm not looking for answers that say something along the lines of "just use data-open", etc... I am looking for an explanation of the above behavior.


Solution

  • open is actually a valid attribute for HTML5 that's meant to be a boolean. If that's the case, I suspect that if you have "open" set at all, the browser is evaluating it as true and returning that it is "open".

    I'd be more curious to know why it's returning "open" instead of "true". Probably due to incomplete implementation in various browsers. In one way or another they may have set that attribute aside for later.

    [addendum: as per comments, this seems to be the way HTML treats booleans]