Use bracket notation
$(document).ready(function() {
var headerContent = $('div').data('url');
console.log(headerContent['header-url']);
console.log(headerContent['footer-url']);
console.log(headerContent['content-url']);
});
Question
I have a data attribute which is having multiple values. How will I get one value out of it ?
<div data-url='{"header-url" : "src/one.html","footer-url" : "src/two.html","content-url" : "src/three.html"}'></div>
$(document).ready(function() {
var headerContent = $('div').attr('data-url');
console.log(headerContent)
});
Solution
Use bracket notation
$(document).ready(function() {
var headerContent = $('div').data('url');
console.log(headerContent['header-url']);
console.log(headerContent['footer-url']);
console.log(headerContent['content-url']);
});
OTHER TIPS
See you can use Bracket Notation
which is available in javascript also you don't need to use .attr()
method of jQuery here as you have a data-*
prefix in that attribute so you can surely make use of .data()
method of jQuery
which works in your case:
$(document).ready(function() {
var headerContent = $('div').data('url');
console.log(headerContent['header-url']); // <--with bracket notation.
});
or if you want to get all the values then you can use $.each()
method for this:
$(document).ready(function() {
var headerContent = $('div').data('url');
$.each(headerContent, function(k, v){
console.log(v); // this logs all the three values.
});
});