Preamble
The question is about HTML element creation with an HTML data attribute, like <object data="foo"></object>.
The Question
Quick question as I stumbled across this a few minutes ago; If I write
$('<div>', { id:"foo", 'class':"bar" });
// <div id="foo" class="bar"></div>
However
$('<object>', { id:"foo", data:"some+data+string" });
// [ <object id="foo"></object> ]
where I expected the output to be
// [ <object id="foo" data="some+data+string"></object> ]
I know about .data. My problem is that
$('<object>', { id:"foo", data:"some+data+string" }).data();
// Object {}
$('<object>', { id:"foo", 'data-foo':"some+data+string" }).data();
// Object {foo:"some+data+string"}
So... why does it not create the HTML attribute data since it is not a data-xxxx attribute name, and therefore does not create any actual data?
Update
I'll reiterate what's written in this question once more.
[...] If I write
$('<div>', { id:"foo", 'class':"bar" });
// <div id="foo" class="bar"></div>
However
$('<object>', { id:"foo", data:"some+data+string" });
// [ <object id="foo"></object> ]
where I expected the output to be
// [ <object id="foo" data="some+data+string"></object> ]
... and once again, I know about .data.
Why doesn't $('<div>', { data: 'foo' }) create <div data="foo"></div>, or in other word, why does it ignore the attribute altogether when creating the element?
Edit
For all those arguing that data is not a valid HTML attribute, well, it is.
Update
As of today, the solution I am using for this use case is
$('<div>', {
attr: {
data: 'foo'
}
});
data-foo, notdata. Just because the jQuerydata()function takes the second part of the data attribute as an argument doesn't mean that it would work that way anywhere else.data-foo.on()andcss()directly in the object, like this, anddata()is a method as well, and it only sets data internally, and jQuery has to look for the methods before it uses the keys as attributes, as it would be too late after the attributes are set, and if the key matches a method, no attribute is set.