Search code examples
javascriptjqueryjquery-data

jQuery.data() working only for appended elements?


In jQuery documentation (jQuery.data()) examples are regarding "data" assigned to elements that are already appended to document, like this

<script>var div = $("div")[0];
    jQuery.data(div, "test", { first: 16, last: "pizza!" });
    $("span:first").text(jQuery.data(div, "test").first);
    $("span:last").text(jQuery.data(div, "test").last);
</script>

I've tried to assign data in the same way, but to a yet NOT appended object, like this

<script>var div = $("<div></div>")[0];
    jQuery.data(div, "test", { first: 16, last: "pizza!" });
    $("span:first").text(jQuery.data(div, "test").first);
    $("span:last").text(jQuery.data(div, "test").last);
</script>

It does not work. Should it?


Solution

  • Remove the [0], works in latest jquery Release

    <script>var div = $("<div></div>");
        jQuery.data(div, "test", { first: 16, last: "pizza!" });
        $("span:first").text(jQuery.data(div, "test").first);
        $("span:last").text(jQuery.data(div, "test").last);
    </script>
    

    Proof: http://jsfiddle.net/Lsa7D/1/