I'm looking in parent divs for child elements that have a specific HTML5 data attribute. This code was working fine:
$('#parent').find('*[data-something]').css('color', 'red');
Then I found out that you can find HTML data attributes using Jquery's data object http://api.jquery.com/data/#data-html5
So I tried...
$('#parent').find($("#parent").data("something")).css('color', 'red');
...and it doesn't work. Does anyone know why?
JSFIDDLE: http://jsfiddle.net/Qct9v/
Note: I have to use find() because I need to search child elements.
It doesn't work because data() is not a filter method, it is a getter/setter method used to get/set the data value.
If you want to use jQuery data then try something like
$("body").find('*').filter(function(){
return $(this).data('something') != undefined
})
Related
there is a div present in my js file
<div id="myid" data="mydata"></div>
when i try to access custom attribute data with pure javascript
var data = document.getElementById('myid').getAttribute('data');
jquery alone
var data = $("#"+myid).attr('data');
above both mwthods are working properly but when i try to used the both jquery and javascript
var data = $("#"+myid).getAtrribute("data");
then is is giving error? but didn't able to get the reason ? can anyone explain please?
You are applying a dom method to a jquery object which causes error instead jquery has a method to convert the selector to the dom element .get():
$("#"+myid).get(0).getAtrribute("data");
alert($('#myid').get(0).getAttribute('data'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="myid" data="mydata"></div>
As you are using a data attribute then better to use data-* attribute and jQuery has a method to get it with .data() method:
<div id="myid" data-mydata="CustomisedData"></div>
then in the jQuery:
$('#myid').data('mydata'); // will give you "CustomisedData"
Because $("#"+myid) is a jQuery instance, not HTML Element object. So you can't use DOM methods on some arbitrary object.
jQuery instance object is an array-like collection of DOM elements. It means that you can extract individual DOM element from it by index if you really need. So in your case you could do this:
$("#" + myid)[0].getAtrribute("data");
jQuery also offers dedicated method for it $.fn.get:
$("#" + myid).get(0).getAtrribute("data");
This should work:
var data = $("#"+myid)[0].getAtrribute("data");
Because to use javascript code, you need to use DOM object but jQuery uses array-like collection object.
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
Noob Question on Data Attribute
I was wondering will using data-attribute in jQuery Selector can bring any trouble in the future?
I'm trying to reduced the usage of .class and #id as jQuery Selector, since most of data I'm working on will generated from data-attribute
example of the code
$(document).ready(function(){
var mydata = $(document).data('my-data-attribute');
});
will the code above slowing the load time?
or
$('[data-suffix-attribute="some_value"]').each(function(){
......
});
or
$('[data-suffix-attribute="delete"]').click(function(){
// delete action happening here
});
will this bring trouble?
$(document).ready(function(){
var mydata = $(document).data('my-data-attribute');
});
The code above will not work. If you want to read the HTML5 data attribute of an element using the jQuery .data() method firstly you need to select the relevant element using a jQuery selector and then you can use the method as is shown below:
var mydata = $('.example').data('suffix');
This will read the value of the data-suffix attribute of an element with a class of "example".
The other important thing to note when using the .data() method is that you have to omit the data- prefix from the selector to read the value stored in that attribute.
The way you have selected the attribute before the .each() method will work:
$('[data-suffix-attribute="some_value"]');
However, it would be better if you can narrow it down to a specific element like:
$('div[data-suffix-attribute="some_value"]');
This is because the first selector will go through every node in the document which will take more time whereas the second will only go through the div tags in the document.
The attribute selector is supported by the native query selectors so it is fine. As far as future is concerned I don't think in near future it will be a problem.
But it will be better if you can use a element selector attached to the attribute selector like $('div[data-suffix-attribute="delete"]')
If you are very worried about performance it will be a better choice to add a class attribute to the desired elements and then use class selector
It would be better to use id in selector which is fast obviously,
If you have multiple data attributes then it is better to use $('[data-suffix-attribute="delete"]').click();.
Instead of this you can use the parent selector for your data-attribute elements like,
$('#parentId').on('click','[data-suffix-attribute="delete"]',function(){
// delete action happening here
});
#parentId contains all data attribute elements
I've used
var activeFilter = $('<li></li>').data('input-id', 'mycustomId');
$('#container').append(activeFilter);
Now I need to get the particular < li > element out of multiple < li > elements in known < ul >.
However the obvious selector doesn't work.
var existing = $('li[data-input-id=mycustomId]');
alert(existing.length);
Useful links:
.prop() vs .attr()
How to get, set and select elements with data attributes?
Summary:
.prop() sets/gets DOM properties.. e.g. className
.attr() sets/gets TAG ATTRIBUTES.. e.g. class, thus making selectors $('obj[class=xxx]') possible.
.data() sets/gets jQuery internal Cache attributes and doesn't map onto attributes or properties.
HOWEVER, in html5 ATTRIBUTES set with .attr() and containing prefix "data-" are being correctly accessible with .data(), BUT NOT VICE VERSA!!
http://jsfiddle.net/wjEvM/
In debugger there is NO property data-input-id listed, but it's accessible through
$('#container li:firstchild').data('input-id');
The question is how do I get (which selector do I have to use) the li (object i.e.) with given value of dataset, like obj.getChildWithData('data-id', 'mycustomId');
OTHER THAN in a loop checking each li's dataset. Or using stupid document.querySelectorAll, because it doesn't do what is needed.
Please explain if applicable if it supposed to work so. Getting data-* attributes set as attributes doesn't allow me to use .data() which is recommended by html5. So I want go get it right.
You are using attribute selector here, this works if you set your HTML5 data as this:
activeFilter.attr('data-input-id', 'mycustomId');
But, you should acces it using correct synthax:
$('#container li:firstchild').data('inputId');
And to answer to your comment, you can retrieve it using .filter():
var existing = $('li').filter(function(){return $(this).data('inputId') === "mycustomId"});
SEE DEMO
Unfortunately for your method, jQuery does not store data set via .data() in the DOM node's data attribute (see this question).
Instead, you'll want to set it with .attr(), and then you can use $('li[data-input-id=mycustomId]'):
$('<li></li>').attr('data-input-id', 'mycustomId');
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..