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)
});

http://jsfiddle.net/taGBL/19/

Was it helpful?

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']);

});

Fiddle

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.
   });
});

Fiddle with $.each() method.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top