HTML5 data DOM's change isn't seen by JQuery - javascript

I'm using HTML5's data to store some informations on a div on my website, and whenever I change the value of this data with jQuery, the DOM's updating well, but jQuery doesn't see the update when I try to retrieve the value.
I update the value of this data with $('#myDiv').attr('data-my_data',value);, and get the value back with $('#myDiv').data('data-my_data').
Here's the fiddle to illustrate my problem.
Is this happening because of some jQuery's initial representation of the DOM that doesn't update?
I don't get it, any help will be appreciated!
Configuration : Chrome 25 - jQuery 1.9.0 - Mac OSx 10.7

you can set the values to the data('yourKey','Yourvalue')
$(yourElement).data('isEdit','1');
according to your Example
$('#myDiv').data('data-my_data','value');
Attr : it will add attributges to the dom object.
prop : it will add properites in memory. so your data will be stroed in dataSet of DOM.
for more info check this attr vs prop

data-* attributes are mapped to dataset DOMString object, use data method as setter, do not use attr for properties.
$('#testDiv').data('test_data', newData).html("My data is : " + newData);
http://jsfiddle.net/zgKdg/

Related

Assign an object to an element as an attribute in java script

I have this scenario where i need to assign a java-script object to div attribute.
var temp["name"]="first";
i assigned it to a div tag attribute using Jquery.
div.attr('data-polygon',temp);
Object [ <div#image01> ]
when i try to retrieve it , it does not come back same.. it is converted as String.
div.attr('data-polygon');
"[object Object]"
Any proper option / alternate to retain the object in attribute? please let me know
Attributes are always strings.
Here are two options for doing this; since you're already using jQuery, the first is probably best:
jQuery's data
jQuery provides the data method for doing this:
// Setting -- notice no "data-" prefix
div.data("polygon", temp);
// Retrieving
varName = div.data("polygon");
Under the covers, traditionally data assigns the element a unique ID and manages a data cache for the element, separate from it. I think in the v3 branch they've updated it to actually store the data on the element (there were memory issues with doing that in Internet Explorer 8 and earlier, which is why jQuery didn't do it before).
Assign it as your own "expando" property
If you don't need to support Internet Explorer 8, you can just create a property on the actual DOM element.
// Setting
rawDiv.myUniquePrefixToAvoidConflicts_polygon = temp;
// Getting
varName = rawDiv.myUniquePrefixToAvoidConflicts_polygon;
Note that to avoid conflicts with the many predefined properties elements have, and future ones they don't have yet, you'll want to use a likely-unique prefix.

What does 'data()' do in '$("#myWidget").data(`ejTE`)'

This works:
var editor = $("#htmlEditor").data('ejRTE');
The question is what does .data('ejRTE') do?
It retrieves the widget which is part of this html:
<textarea id="htmlEditor" value.bind="entity.content"
ej-rte="e-width:100%"
ref="textArea"
style="height: 220px"></textarea>
How do I retrieve it without jQuery.
jQuery.data() Store arbitrary data associated with the specified element and/or
return the value that was set.
So basically the widget stores some data in the element htmlEditor indexed ejRTE, I bet it is a custom object used by this tool.
var editor = $("#htmlEditor").data('ejRTE');
then editor will hold the object stored by the widget for this element
If you set data like this $(#myWidget).data('foo', 'myFoo') then jQuery will create an object called 'jQuery224059863907884721222' on myWidget which it uses to store the value.
I am guessing that the number is an arbitrary datetime value.
I stepped through the jQuery code, and it's not practical to replace it. I thought it might be just a line or two of code.

Assigning individual keys of object stored in jQuery.data()

I have custom data stored on elements using jQuery.data() method.
<div id="mydiv" data-test='{"1":"apple", "2":"banana"}'>Custom data</div>
I know I can access individual keys of the object stored in data-test using
$('#mydiv').data('test')["1"]
But is it ok to re-assign individual keys like this ? It works but it isn't documented. Secondly, on inspecting the element using browser's developer tools, I still see the old value i.e. "apple" in this case. JSFiddle
$('#mydiv').data('test')["1"] = "pear"
Update
- Found more related Q&A (not really duplicate because my primary question was about assigning individual keys of the object)
Unable to set data attribute using jQuery Data() API
Why don't changes to jQuery $.fn.data() update the corresponding html 5 data-* attributes?
Can't update data-attribute value : Good discussion in comments of answers
Using .data() to set a value, won't change the values in the element while you inspect it, it would store that data internally. If you want to reflect those changes to the DOM element, then you should use .attr() like this,
$('#mydiv').data('test')["1"] = "pear"
$('#mydiv').attr('data-test', JSON.stringify($('#mydiv').data('test')));
DEMO
Inspect that particular element to verify the changes.
Try this
$('#mydiv').data('test')["1"] = "pear";
$('#mydiv').attr('data-test',function(_,attr){
return JSON.stringify(attr);
});

dataset vs .data - Difference?

I am reading some values in data attribute fields. I have seen two easy ways to read the data as shown below:
var webappData = document.getElementById('web-app-data'),
rating = webappData.dataset.rating;
OR
var effectData = $('.effects-list li'),
creative = effectData.filter('[data-creative]').data("creative");
My question is which of these has better performance or do they really differ?
I have a page with many data attributes that I am accessing and I would like to use the method that has the best performance.
Any guidance on understanding the difference between the two would be appreciated. While I am looking at performance specifically if there are other reasons to use one over the other I would like to know this as well.
dataset is a native property of an element that contains the data attributes, it's a new(ish) addition and as such is only supported in IE11+, Chrome 8+, FF 6+ etc.
A more cross browser solution would be to get the attribute directly
webappData.getAttribute('data-rating');
data() is a jQuery method, and other than using the HTML5 data attribute to set the inital value if none exists internally, it has nothing in common with dataset.
data() stores whatever data you pass it in an internal object created by jQuery, so this for instance would fail
$(element).data('key', 'value');
element.dataset.key // undefined
as the data is not stored in the attributes at all, but internally by jQuery.
The jQuery equivalent of getting and setting the data attribute would be attr()
$(element).attr('data-key', 'value');
The native methods are probably faster, but as they are not really comparable to jQuery's data() it doesn't really matter, but for getting the data attribute I would think the fastest method with the best browser support would be
var rating = webappData.getAttribute('data-rating');

How to get data stored in a DOM element?

I have a DOM element of class bar that stores data foo, which is the id of another DOM element.
<div class="bar" data="foo">...</div>
When I hover over such element, I want to get the DOM element that the data (id) points to. I did this:
$(".bar").hover(function(){alert($("#"+$(this).data()));});
But when I hover, I get this error:
Uncaught Error: Syntax error, unrecognized expression: #[object Object]
What am I doing wrong, and how can I fix it?
You are confusing the data() method with the element's data attribute.
The data() method returns an unrelated object of data attached to the element and not the string you are looking for.
Solution 1 - data as an attribute
To get the value you're looking for in your example, you should query the attribute with the attr() method:
$(".bar").hover(function(){alert($("#"+$(this).attr('data')));});
Solution 2 - data as an object
Using the data() method you can manually attach information to the element:
$('.bar').data('data','foo');
$(".bar").hover(function(){alert($("#"+$(this).data('data')));});
Note how in this case 'data' is just an arbitrary name for a key in the element's data object. For more on the data() method see the jQuery manual
Solution 3 - data as an object and HTML5 attribute
I believe your original intention was to query the data attribute as an HTML5 data-attribute, that according to the jQuery documentation should be automatically pulled in to jQuery's data object.
However, note that according to the HTML5 specification, HTML5 data-attributes are expected to have a data- prefix. So in order for your example to work, the attribute cannot be named data but rather data-something. For example:
<div class="bar" data-something="foo">...</div>
Which you can then access with jQuery's data() method:
$(".bar").hover(function(){alert($("#"+$(this).data('something')));});
Note how data-something is accessed with data('someting'), since jQuery automatically removes the data- prefix.
you need to access the attribute with the attr function.
$(".bar").hover(function() {
alert($("#"+$(this).attr('data')));
});
I know no one is asking for this, but here is how to do this in modern browsers without jQuery:
for (bar of document.getElementsByClassName('bar')) {
bar.addEventListener('hover', e => alert(
document.getElementById(e.target.attributes.data.value)
))
}

Categories

Resources