Taylor Gomez
Taylor Gomez

Reputation: 330

Make a js code with a special format

I want get date-type and date-title in div.Img and make it as following format by jquery in the end putting it in a jQuery function, How is it?

This is div.Img:

<div class="Img" date-type="http://fancyapps.com/fancybox/demo/1_b.jpg" date-title="manual 1st title"></div>
<div class="Img" date-type="http://fancyapps.com/fancybox/demo/2_b.jpg" date-title="2nd title"></div>
<div class="Img" date-type="http://fancyapps.com/fancybox/demo/3_b.jpg" date-title="3rd title"></div>

This is my format: i want get in result as fllowing fomat of date-type and date-title in div.Img, with { } and ,.

    {
        href : 'http://fancyapps.com/fancybox/demo/1_b.jpg',
        title : 'manual 1st title'
    },
    {
        href : 'http://fancyapps.com/fancybox/demo/2_b.jpg',
        title : '2nd title'
    },
    {
        href : 'http://fancyapps.com/fancybox/demo/3_b.jpg',
        title : '3rd title'
    }

Please give me a example in jsfiddle.net

Upvotes: 0

Views: 41

Answers (3)

Satpal
Satpal

Reputation: 133403

Custom attribute should be data-* prefixed not date-*

<div class="Img" data-type="http://fancyapps.com/fancybox/demo/1_b.jpg" data-title="manual 1st title">1</div>

Then .map() can be used in conjunction with .data()

var arr = $('div.Img').map(function (elem) {
    return {
        href: $(this).data('type'),
        title: $(this).data('title')
    }
}).get();

console.log(arr);

Fiddle example

Upvotes: 1

Sudharsan S
Sudharsan S

Reputation: 15393

Use .map() in Jquery.

The $.map() method applies a function to each item in an array or object and maps the results into a new array

var res = $(".Img").map(function() {
    return {"href":$(this).attr('date-type'),
            "title":$(this).attr('date-title')
           }
}).get();

 console.log(res);

Fiddle

Upvotes: 0

Matteo Tassinari
Matteo Tassinari

Reputation: 18584

Here is a working code snippet sample.

function getDivInfo($div) {
  return {
    "href": $div.attr("date-type"),
    "title": $div.attr("date-title")
  };
}

$(function() {
  var div_info = [];
  
  $('div.Img').each(function() {
    div_info.push(getDivInfo($(this)));
  });
  
  console.log(div_info);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="Img" date-type="http://fancyapps.com/fancybox/demo/1_b.jpg" date-title="manual 1st title"></div>
<div class="Img" date-type="http://fancyapps.com/fancybox/demo/2_b.jpg" date-title="2nd title"></div>
<div class="Img" date-type="http://fancyapps.com/fancybox/demo/3_b.jpg" date-title="3rd title"></div>

Please note that custom attributes should begin with data- and not date-.

Upvotes: 0

Related Questions