jquery data do not match dom attribute - javascript

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/

Related

jQuery data attribute is being returned differently for multiple requests

I have an element:
<a id="contactUsLink" class="modalButton homepageButton modalOpenButton" href="#" data-modal='{ldelim} "target" : "#contactDialogue", "action" : "open" {rdelim}'>Contact Us</a>
I assign a closure to the jQuery click event
$('#contactUsLink').click(function(e) {
e.preventDefault();
var data = $(this).data('modal');
modeless.modal(this);
});
I process the data attribute in my namespaced javascript function nameless.modal(), I do various things with the DOM including animating various divs etc.
When I click the link again the varaiable data is returning the data attribute for another element.
I'm very confused. Obviously my other code is interfering with jQuery somehow, but as all my variables and function names are in my own namespace....how?
Have a missed something else?
It seems that jQuery caches data attributes.
Line 3614 - https://code.jquery.com/jquery-2.1.4.js
No idea why it is return the cached data for another object but I suspect Ive found a bug in the implementation as to how the cache retrieves data.
jQuery.removeData() will clear this cache.
jQuery does not dynamically update its internal data. When using data-attributes, I target the attribute instead.
Check out this demo:
// jQuery data - does not update dynamically
$(this).data('test');
// element attribute - does update dynamcially
$(this).attr('data-test')

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

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

Getting attribute set by a function jQuery

I have a function attached to the div #Browse's click event that toggles a variable isOpen to true or false. Another click event has the following statements
alert($("#Browse").attr('isOpen'));
alert(document.getElementById('Browse').isOpen);
The first one yields "undefined" while the second one says true or false and is correct. How can I get the value of isOpen using jQuery?
Use data attributes to both set and get the data:
// to set
$("#Browse").data('isOpen', true)
// to get
$("#Browse").data('isOpen')
Documentation
jQuery data method - http://api.jquery.com/data/
There is no "jQuery way" to do this, because isOpen is an ad-hoc property. If you are able to change how the property is set, follow the recommendations in Chris' answer.
Otherwise, the closest you can get is to use jQuery to get the DOM element, and then unwrap it:
alert($("#Browse")[0].isOpen);
With new versions of jQuery, you need to use .prop to get this.
alert($("#Browse").prop('isOpen'));
To get access to the dom element in jQuery, you have to get the element by its index in the jQuery collection: With an id, there's hopefully only one element in your collection, so you can use get(0)
$('#Browse').get(0).isOpen;
For more convinient setting of attributes on jQuery elements, just use the data method

HTML5 custom attribute updated value

How do i get the value of an html5 attribute using jQuery ?
<button data-direction="next" data-next="2"></button>
I want to be able to get the newest set value of data-next.
When i change the value dynamically using javascript and then try to get it using
$('[data-direction="next"][data-next]').data('next'),
it always returns the data as set when loading the page not after being updated - in this case 2.
$('[data-direction="next"][data-next]').attr('data-next') should work..
I concur with #Pierre. Use the attr() method to retrieve the desired value.
A point to note, your selector could turn out to be slower. Check this article out.

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