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

StackOverflow https://stackoverflow.com/questions/9525334

Question

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.

Was it helpful?

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]

OTHER TIPS

Did some testing, and for some reason this seems to work:

document.getElementById('myID').getAttribute('open');

While jQuery does not work for neither .prop() or .attr()

Strange indeed?

FIDDLE

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top