JQuery creates a new element with the HTML `data` attribute

Preamble

The question is about creating an HTML element with an HTML attribute data, for example <object data="foo"></object>.

Question

The quick question is when I stumbled upon 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 doesn't it create an HTML attribute data, since it is not an attribute of an attribute data-xxxxand therefore does not create any real data?

Update

I will repeat again what is written in this question.

[...] 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 again, I know about .data.

Why $('<div>', { data: 'foo' })doesn’t it create, <div data="foo"></div>or in other words, why does it generally ignore the attribute when creating the element?

Edit

, , data HTML, , .

Update

, , -

$('<div>', {
  attr: {
    data: 'foo'
  }
});
+4
1

jQuery ,

$('<div />', { 
    id      : "foo",  
    'class' : "bar",
    text    : "test",          // jQuery text() is called,
    html    : '<span></span>', // jQuery html() is called,
    css     : {                // jQuery css() is called,
        color: 'red'
    },
    on : {                     // calls jQuery .on('click' ...
        click: function() {
             alert
        }
    }
});

, data="" , , <object>, jQuery, , , data="", jQuery data().

, , data()

$('<object />', {data : 'somedata'});

, , -, , jQuery , , , jQuery attr() ,

$('<object>', { id:"foo", 'Data' : "some+data+string" });
$('<object>', { id:"foo", 'daTa' : "some+data+string" });

, ,

<object id="foo" data="some+data+string"></object>

FIDDLE

+7

Source: https://habr.com/ru/post/1535181/


All Articles