Jquery clone() doesn't clone new value set wit data() - javascript

Using jquery data() to set data attribute of an element, like so:
HTML:
<div id="some-el" data-number="0"></div>
JQ:
$("#some-el").data("number",1);
As we know, data changes variable internally. So inside inspector you cannot actually see that new value is 1. But this aside, if I do clone on the element with new data value, jquery clones original dom element without current data value!!!
$("#some-el").clone();
Results in <div id="some-el" data-number="0"></div> both internally and visibly!
I was thinking I could avoid this problem by simply using attr("data-number",1);
Anyways, I wanted to ask you if this is correct behaviour of dat()? Is what I'm seeing expected? and WHY?

I think clone can accept a boolean to indicate a Clone with data and events, so Clone(true) should work: http://api.jquery.com/clone/
Here's a fiddle that works: http://jsfiddle.net/2pdNL/

.data() is not setting the value in DOM.
The data- attributes are pulled in the first time the data property is
accessed and then are no longer accessed or mutated (all data values
are then stored internally in jQuery)
But here is a workaround, instead of using
$("#some-el").data("number",1);
Interact directly to DOM like
$("#some-el").attr("data-number",1);
JSFiddle
Also check this answer

Related

jQuery caches elements selected?

So I'm using this code to:
$('.something').on('click', function () {
console.log($(this).data('id'));
}
And for some reason, if I modify the data-id using the inspector, jQuery still sees the id that was there in the beginning. However, I tried the same thing using JS and it does see the changes. This makes me wondering if jQuery caches in some way the elements selected and uses them instead of the actual DOM.
Can someone please explain what happens and how jQuery does the event binding in the background?
Later edit: I want to specify that I'm talking about the "data-" attribute that I put in the HTML, not about the '.data()' provided by jQuery. Not sure if it's the same thing.
jQuery caches elements selected?
No. But the data managed by data is stored in an object cache maintained by jQuery, keyed by a unique identifier jQuery adds to the element (so it can look up the data). data is only initialized from data-* attributes, it is not an accessor for them. It's both more and less than that.
If you're interested, you can see that as an "expando" property on the element instance, it'll start with "jquery" and have a long number attached to it (currently; it's undocumented — for good reason — so this may change):
var foo = $("#foo");
console.log(foo.data("info")); // hi there
console.log("Expando name: " + Object.getOwnPropertyNames(foo[0]).find(name => name.startsWith("jQuery")));
<div id="foo" data-info="hi there"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Where does jquery put .val() on a DIV?

jQuery (all versions tested up through 2.1.0) allows me to call .val("some value") on a DIV object to set a value on the DIV. It is not displayed and doesn't show up as an HTML5 data property in Chrome Developer Tools. And yet I can fetch the result later with a call to .val().
For example (from http://jsfiddle.net/X2nr6/ ):
HTML:
<div id="mydiv" style="display: none;">Some text</div>
<div id="debug"></div>
Javascript:
$('#mydiv').val('A value attached .');
$('#debug').text( $('#mydiv').val() );
Displayed result:
A value attached.
Where is the value stored? Not knowing where it is stored makes me worry that I am relying on a hack.
jQuery is just assigning to a value property on the div object (the HTMLDivElement instance for that div), even though it doesn't normally have one. Creating new properties on elements is allowed in every browser I've ever seen, so it works. I wouldn't use val with divs on a regular basis, though.
Here's a non-jQuery example:
var div = document.createElement('div');
console.log('value' in div); // false, divs don't normally have a value property
div.value = 42;
console.log('value' in div); // true, we've created a property on the element
console.log(div.value); // 42
Or the same sort of thing using jQuery:
var $div = $("<div>");
display(typeof $div.prop('value'));
$div.val(42);
display(typeof $div.prop('value'));
display($div.prop('value'));
This business of creating new, custom, non-standard properties on elements is called creating "expando" properties. They can be very handy. (jQuery uses them internally, for instance, to manage the data cache and a few other things — if you look closely at a DOM element you've set data on using data, you'll see a property with a name like jQuery1110028597884019836783; that's the key jQuery uses to find the element's data in jQuery's internal data cache. jQuery doesn't store the data in an expando on the element, because of IE garbage collection issues; it stores the key there, and the data in a JavaScript object.)
It stores it on a value property on the DOM object. You can see if by running your code and then inspecting the element in a DOM inspector. In Chrome, the value property will be listed under div#mydiv in the properties tab.
HTMLDivElement objects don't officially support such a property, so you are relying on a hack.
Use data() to store arbitrary data on an element.
$('#mydiv').data("myCustomValue", 'A value attached .');
Although the above answers are accurate, I'd like to complete something out.
jQuery is designed around the concept of wrapping all HTML elements in the jQuery object. That jQuery object happens to be an array that can hold more than one element.
jQuery also goes out of its way to hide this fact from you so that the average jQuery developer never has to worry about exactly what he has -- simply call the right method and the magic happens.
(You see this if you do a $(".someClassYouHaveLotsOf").hide() or $(".someClassYouHaveNoneOf").hide()`.)
jQuery's val() method is just a wrapper for accessing an HTML input element's value property. Since jQuery doesn't throw errors unless there is really no way what-so-ever, it silently helps you by accessing the value property on whatever HTML element it happens to have. div span or whatever.
In most browsers, this works -- mostly enough.
If you are really interested in setting values on HTML elements for use later, the data() method is far better suited. Straight HTML would use <element>.setAttribute("data-key", "value");
And that is about the only time you'll see me using the HTML attributes over properties, BTW.

jQuery - Clone <div> with form elements, including their values

I have a Django formset, which has lots of form elements. I have a working method to create a new empty form, but I also need a solution to copy a form. Technically, all forms are in a div, like this:
<form>
...
<div class="subform">
...
</div>
...
</form>
The problem is, that in latest jQuery versions, html and replaceWith methods don't handle input values, so they create empty form elements instead - which is not the behavior I need. Of course I could implement an algorithm which iterates over all the elements, copies them and sets their values, but I'd like to avoid it if possible.
I want to replace an existing form with the copied values.
Yes can use clone() and replaceAll() instead of html()/replaceWith(). clone() will preserve the value properties of your <input> elements, and can even preserve event handlers and custom data.
You can write something like:
var theForm = $("selector-matching-your-form");
theForm.clone(true).replaceAll(theForm);
Frédéric has a brilliant answer, and it took me a while to understand it. Here is a different version:
Make a variable that references an element.
var someElement = $("input#some-element");
Clone the element
var cloneOfElement = $someElement.clone(true);
Use the clone to replace original element, by using the variable that references the original element.
cloneOfElement.replaceAll( $someElement );
--
From the replaceAll() documentation:
"The .replaceAll() method is similar to .replaceWith(), but with the source and target reversed."

jquery data do not match dom attribute

I have an weird issue with jquery data function. Here is the fiddle
As you can see I update the active data but I cannot see the dom data-active attribute value change, although I re-query the active data, It writes the changed value.
$.data() do not update the attribute on the dom when I inspect it.
jQuery data api does not depends on the element attribute although it uses data-<key> to fetch the initial value if it is available.
jQuery uses an internal javascript object to maintain the data value of objects
If you want to update the attribute then you will have to use .attr('data-<key>', '<value>')
You will need to use attr as .data will not update the actual DOM node attribute -
$($('li')[1]).attr('data-active', true);
http://api.jquery.com/data/

Add some properties to a <div> element

I want to add some properties to a <div> element. All of the below works except for the .data(). I cannot see it appear in Firefox/Firebug.
$('#menu-container')
.css('background-image','url("'+big_image+'")')
.addClass('click_2')
.data("new_link", "new_link.html")
.css('z-index',"99");
Am I doing it wrong?
data is not just any ordinary attribute you can add, it is a way to attach objects and data to DOM elements. You can't see it in the HTML source or in Firebug, but you can query it using .data()
The data itself is not stored on the element. It's actually stored in $.cache
.data() is working but it won't show up as an element's attribute.
If you wanted to see it working you can try console.log($('#menu-container').data('new-link'));
If attributes are what you want then you can do .attr('new-link','new-link.html')
Use
$('#menu-container').attr('data-new_link','new_link.html');
it will appear in firebug, and you can also use the expected jQuery behavior
$('#menu-container').data('new_link');
to retrieve the value stored..
But there is really no need to do it this way. It gets stored at the .data() collection, regardless of being added as an attribute to the DOM element..

Categories