Ryan Exlay Ryan Exlay - 3 months ago 12
Javascript Question

get multi data atrributes from element classes of response html

how to get muttiple data attribute from element classes of response html.
I can extract only data.

this is response.html



<div class="book" data-name="frozen" data-author="micheal" data-price="30">
Frozen
</div>
<div class="book" data-name="unbroken" data-author="jimmy" data-price="25">
Unbroken
</div>
<div class="book" data-name="carry on" data-author="alex" data-price="32">
Carry On
</div>





Ajax code here

function getData($scope){
$.ajax({

url: "/response.html",
dataType: "html",
success: function(response) {
var $response = $(response);
// not working
// var $book-data = $response.find('div.book').data({'name','author','price'});
var $bookData = $response.find('div.book').data('name');
alert($bookData);
}
});
}


I wish to get book-data as json or array to display in angular.

Answer

Pretty easy:

var allData = [];
$('.book').each(function(i){
	allData.push( $(this).data() );
});
console.log( allData );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="book" data-name="frozen" data-author="micheal" data-price="30">
    Frozen
</div>
<div class="book" data-name="unbroken" data-author="jimmy" data-price="25">
    Unbroken
</div>
<div class="book" data-name="carry on" data-author="alex" data-price="32">
    Carry On
</div>