2

I have a element defined as follows:

<span class="road-btn js-road-btn" data-lat-s=' + row.LatL + ' data-lng-s=' + row.LongL + ' data-lat-e=' + row.LatD + ' data-lng-e=' + row.LongD +'> <i class="icon-pin"></i ></span > 

I have performed a click event on this element as :

$('.js-road-btn').on('click', function () {
    var latS = $(this).attr('data-lat-s');
    var longS = $(this).attr('data-lng-s');
    var latE = $(this).attr('data-lat-e');
    var longE = $(this).attr('data-lng-e');
});

Instead of getting each attribute separately, I want to retrieve all the attributes values as a whole. Then I access the properties separaretly. How can I achieve this in jquery ?

benvc
  • 14,448
  • 4
  • 33
  • 54
crazydev
  • 575
  • 2
  • 9
  • 30
  • 2
    https://api.jquery.com/data/. – deEr. Apr 25 '18 at 08:33
  • 1
    see https://stackoverflow.com/questions/4187032/get-list-of-data-attributes-using-javascript-jquery – Mohsen Zia Apr 25 '18 at 08:33
  • 1
    Possible duplicate of [Get list of data-\* attributes using javascript / jQuery](https://stackoverflow.com/questions/4187032/get-list-of-data-attributes-using-javascript-jquery) – freedomn-m Apr 25 '18 at 08:35

2 Answers2

4

You could use the jQuery method .data() like :

$(this).data(); //Will return the set of all the data-* attributes

$('.js-road-btn').on('click', function() {
  var attributes = $(this).data();

  console.log(attributes);

  alert(attributes.lngE);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<span class="road-btn js-road-btn" data-lat-s='1' data-lng-s='2' data-lat-e='3' data-lng-e='4'> Click me </span >
Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
2

As the values are all stored in data-* attributes, you can use data() (with no arguments) to retrieve them all in a single object:

$('.js-road-btn').on('click', function() {
  var data = $(this).data();
  console.log(data);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="road-btn js-road-btn" data-lat-s="lat-s" data-lng-s="lng-s" data-lat-e="lat-e" data-lng-e="lng-e"> 
  Click me
</span>
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339