Access 'data-' attribute without jQuery
On here I found this example:
<div id='strawberry-plant' data-fruit='12'></div>
<script>
// 'Getting' data-attributes using getAttribute
var plant = document.getElementById('strawberry-plant');
var fruitCount = plant.getAttribute('data-fruit'); // fruitCount = '12'
// 'Setting' data-attributes using setAttribute
plant.setAttribute('data-fruit', '7'); // Pesky birds
</script>
So it would appear very doable.Update: Since Microsoft is now (2020) phasing out the old Internet Explorer engine in favour of a Chromium based Edge, the dataset
property is likely to work everywhere. The exception will, for a time, be organizations and corporate networks where IE is still forced. At the time of writing this though - jsPerf still shows the get/setAttribute method as being faster than using dataset, at least on Chrome 81.
Getting array out of data attribute without jQuery
jQuery's .data()
method automatically tries to convert the string in your custom data attribute to whatever type it appears to be (in this case an array). JavaScript just treats it as a string, so you need to parse the string to get the same array output you get with jQuery. For example:
// jQuery approach
const jqtest = $('div').data('toshow');
console.log(jqtest);
// Plain JavaScript approach
const jstest = JSON.parse(document.querySelector('div').dataset.toshow);
console.log(jstest);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div data-toshow='["tblp"]'></div>
How can I get the data-id attribute?
To get the contents of the attribute data-id
(like in <a data-id="123">link</a>
) you have to use
$(this).attr("data-id") // will return the string "123"
or .data()
(if you use newer jQuery >= 1.4.3)$(this).data("id") // will return the number 123
and the part after data-
must be lowercase, e.g. data-idNum
will not work, but data-idnum
will. Store Object in data-attribute without jQuery
Use JSON.stringify()
before storing the data in the attribute. It is basically serializing the data into a string.
var div = document.getElementById("testDiv");
var obj = JSON.stringify({name: "Test1", value: 100});
div.setAttribute("data-obj", obj);
var arrayAsJSON = JSON.stringify([59, 40, 3, 2, 1, 0]);
div.setAttribute("data-arr", arrayAsJSON);
Then use JSON.parse()
after you fetch the attribute value and before presenting it. This will deserialize it back to a javascript object, array or simple value, depending on your case. How to select an item by attribute without jquery?
You can do it with document.querySelectorAll('[data-key=' + objectId + ']')
and loop through all results
var allKeys = document.querySelectorAll('[data-key=' + objectId + ']');
[].forEach.call(allKeys, function(elem){
console.log(elem); //Do your stuff with each element
});
Find an element in DOM based on an attribute value
Update: In the past few years the landscape has changed drastically. You can now reliably use querySelector
and querySelectorAll
, see Wojtek's answer for how to do this.
There's no need for a jQuery dependency now. If you're using jQuery, great...if you're not, you need not rely it on just for selecting elements by attributes anymore.
There's not a very short way to do this in vanilla javascript, but there are some solutions available.
You do something like this, looping through elements and checking the attribute
If a library like jQuery is an option, you can do it a bit easier, like this:
$("[myAttribute=value]")
If the value isn't a valid CSS identifier (it has spaces or punctuation in it, etc.), you need quotes around the value (they can be single or double):$("[myAttribute='my value']")
You can also do start-with
, ends-with
, contains
, etc...there are several options for the attribute selector. How to get data attribute in ie 7?
jQuery can help ... the data attribute works with the data() function in jQuery.
$(srcElement).data('pk');
You can use it with any data attribute, for example, if you had:<div id="DivId" data-something="foo" data-somethingElse="bar">
You can get the data out by:$('#DivId').data('something');
$('#DivId').data('somethingElse');
To set data:$('#DivId').data('something', 'foo');
$('#DivId').data('somethingElse', 'bar');
Here is a link to jQuery .data()EDIT:
I think you want:
$('.image').click(function () {
openSlide($(this).data('pk'), false);
});
How to set data attributes in HTML elements
HTML
<div id="mydiv" data-myval="10"></div>
JSvar a = $('#mydiv').data('myval'); //getter
$('#mydiv').data('myval',20); //setter
DemoReference
From the reference:
jQuery itself uses the .data()
method to save information under the names 'events' and 'handle', and also reserves any data name starting with an underscore ('_') for internal use.
It should be noted that jQuery's data()
doesn't change the data
attribute in HTML.So, if you need to change the data
attribute in HTML, you should use .attr()
instead.
HTML
<div id="outer">
<div id="mydiv" data-myval="10"></div>
</div>
jQuery:alert($('#outer').html()); // alerts <div id="mydiv" data-myval="10"> </div>
var a = $('#mydiv').data('myval'); //getter
$('#mydiv').attr("data-myval","20"); //setter
alert($('#outer').html()); //alerts <div id="mydiv" data-myval="20"> </div>
See this demo jQuery selectors on custom data attributes using HTML5
$("ul[data-group='Companies'] li[data-company='Microsoft']") //Get all elements with data-company="Microsoft" below "Companies"
$("ul[data-group='Companies'] li:not([data-company='Microsoft'])") //get all elements with data-company!="Microsoft" below "Companies"
Look in to jQuery Selectors :contains is a selectorhere is info on the :contains selector
Pass javascript function as data-* attribute and execute
One way is to use eval()
jQuery(".container").on("click", "button.marker", function (e) {
var callback = jQuery(e.currentTarget).data("callback");
var x = eval(callback)
if (typeof x == 'function') {
x()
}
});
Demo: FiddleNote: Make sure it is safe in your environment, ie there is no possibility of script injection because of bad input from users
- Why is using the JavaScript eval function a bad idea?
- When is JavaScript's eval() not evil?
- eval() isn’t evil, just misunderstood
- Eval is Evil, Part One
Related Topics
What Is the Most Efficient Way to Reverse an Array in JavaScript
How to Auto-Slide the Window Out from Behind Keyboard When Textinput Has Focus
How to Create an Auto-Complete Combobox
JavaScript - Telling Setinterval to Only Fire X Amount of Times
How to Call a Dynamically-Named Method in JavaScript
Angular 2 Karma Test 'Component-Name' Is Not a Known Element
Angularjs Browser Autofill Workaround by Using a Directive
Why Are Es6 Classes Not Hoisted
Angular 2 Router Event Listener
Domnodeinserted Equivalent in Ie
Invoke a Callback at the End of a Transition
How to Bind Bootstrap Popover on Dynamic Elements
React Routing Works in Local MAChine But Not Heroku
Clear JavaScript Console in Google Chrome