In jQuery you can create new elements and define properties on them in one step:
$("<div>", {title: "Hey there!", text: "I'm a DIV!"});
This produces:
<div title="Hey there!">I'm a DIV!</div>
Is there a way to do the same with an existing element? The following does not work:
$("#theDiv", {title: "Hey there!", text: "I'm a DIV!"});
Turns out things are rather easy. jQuery uses
.attr()for this.Note the second parameter set to
true. This causes jQuery to use the same mechanism that it uses for freshly created elements.Even function parameters work as expected:
(See this jsFiddle.)
Consequently, this will also work for event bindings, CSS modifications and all the other things jQuery can do:
(See this jsFiddle.)
This is undocumented, so it could change in any dot release without being listed in the release notes, but it seems unlikely to and it’s easy to test it when upgrading jQuery.