[javascript] How to get the data-id attribute?

I'm using the jQuery quicksand plugin. I need to get the data-id of the clicked item and pass it to a webservice. How do I get the data-id attribute? I'm using the .on() method to re-bind the click event for sorted items.

_x000D_
_x000D_
$("#list li").on('click', function() {_x000D_
  //  ret = DetailsView.GetProject($(this).attr("#data-id"), OnComplete, OnTimeOut, OnError);_x000D_
  alert($(this).attr("#data-id"));_x000D_
});
_x000D_
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>_x000D_
_x000D_
<ul id="list" class="grid">_x000D_
  <li data-id="id-40" class="win">_x000D_
    <a id="ctl00_cphBody_ListView1_ctrl0_SelectButton" class="project" href="#">_x000D_
      <img src="themes/clean/images/win.jpg" class="project-image" alt="get data-id" />_x000D_
    </a>_x000D_
  </li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

This question is related to javascript html jquery custom-data-attribute

The answer is


This piece of code will return the value of the data attributes eg: data-id, data-time, data-name etc.., I have shown for the id

<a href="#" id="click-demo" data-id="a1">Click</a>

js:

$(this).data("id");

// get the value of the data-id -> a1

$(this).data("id", "a2");

// this will change the data-id -> a2

$(this).data("id");

// get the value of the data-id -> a2


For those looking to dynamically remove and re-enable the tooltip, you can use the dispose and enable methods. See https://getbootstrap.com/docs/4.0/components/tooltips/#tooltipdispose


The issue is you are not specifying the option or selected option of dropdown or list, Here is an example for dropdown, i am assuming a data attribute data-record.

$('#select').on('change', function(){
        let element = $("#visiabletoID");
        element.val($(this).find(':selected').data('record'));
    });

var id = $(this).dataset.id

works for me!


If we want to retrieve or update these attributes using existing, native JavaScript, then we can do so using the getAttribute and setAttribute methods as shown below:

Through JavaScript

<div id='strawberry-plant' data-fruit='12'></div>

<script>
// 'Getting' data-attributes using getAttribute
var plant = document.getElementById('strawberry-plant');
var fruitCount = plant.getAttribute('data-fruit'); // fruitCount = '12'

// 'Setting' data-attributes using setAttribute
plant.setAttribute('data-fruit','7'); // Pesky birds
</script>

Through jQuery

// Fetching data
var fruitCount = $(this).data('fruit');
OR 
// If you updated the value, you will need to use below code to fetch new value 
// otherwise above gives the old value which is intially set.
// And also above does not work in ***Firefox***, so use below code to fetch value
var fruitCount = $(this).attr('data-fruit');

// Assigning data
$(this).attr('data-fruit','7');

Read this documentation


Important note. Keep in mind, that if you adjust the data- attribute dynamically via JavaScript it will NOT be reflected in the data() jQuery function. You have to adjust it via data() function as well.

<a data-id="123">link</a>

js:

$(this).data("id") // returns 123
$(this).attr("data-id", "321"); //change the attribute
$(this).data("id") // STILL returns 123!!!
$(this).data("id", "321")
$(this).data("id") // NOW we have 321

using jQuery:

  $( ".myClass" ).load(function() {
    var myId = $(this).data("id");
    $('.myClass').attr('id', myId);
  });

Try

this.dataset.id

_x000D_
_x000D_
$("#list li").on('click', function() {_x000D_
  alert( this.dataset.id );_x000D_
});
_x000D_
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>_x000D_
_x000D_
<ul id="list" class="grid">_x000D_
  <li data-id="id-40" class="win">_x000D_
    <a id="ctl00_cphBody_ListView1_ctrl0_SelectButton" class="project" href="#">_x000D_
      <img src="themes/clean/images/win.jpg" class="project-image" alt="get data-id >>CLICK ME<<" />_x000D_
    </a>_x000D_
  </li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_


HTML

<span id="spanTest" data-value="50">test</span>

JS

$(this).data().value;

or

$("span#spanTest").data().value;

ANS : 50

Works for me!


If you are not concerned about old IE browsers, you can also use HTML5 dataset API

HTML

<div id="my-div" data-info="some info here" data-other-info="more info here">My Awesome Div</div>

JS

var myDiv = document.querySelector('#my-div');

myDiv.dataset.info // "some info here"
myDiv.dataset.otherInfo // "more info here"

Demo: http://html5demos.com/dataset

Full browser support list: http://caniuse.com/#feat=dataset


I use $.data - http://api.jquery.com/jquery.data/

//Set value 7 to data-id 
$.data(this, 'id', 7);

//Get value from data-id
alert( $(this).data("id") ); // => outputs 7

Surprised no one mentioned:

<select id="selectVehicle">
     <option value="1" data-year="2011">Mazda</option>
     <option value="2" data-year="2015">Honda</option>
     <option value="3" data-year="2008">Mercedes</option>
     <option value="4" data-year="2005">Toyota</option>
    </select>

$("#selectVehicle").change(function () {
     alert($(this).find(':selected').data("year"));
});

Here is the working example: https://jsfiddle.net/ed5axgvk/1/


I have a span. I want to take the value of attribute data-txt-lang, which is used defined.

$(document).ready(function ()
{
<span class="txt-lang-btn" data-txt-lang="en">EN</span>
alert($('.txt-lang-btn').attr('data-txt-lang'));
});

Accessing data attribute with its own id is bit easy for me.

$("#Id").data("attribute");

_x000D_
_x000D_
function myFunction(){_x000D_
  alert($("#button1").data("sample-id"));_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<button type="button" id="button1" data-sample-id="gotcha!" onclick="myFunction()"> Clickhere </button>
_x000D_
_x000D_
_x000D_


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to custom-data-attribute

How can I get the values of data attributes in JavaScript code? jQuery: get data attribute jQuery find element by data attribute value Using HTML data-attribute to set CSS background-image url Adding data attribute to DOM Why does JS code "var a = document.querySelector('a[data-a=1]');" cause error? How to set data attributes in HTML elements jQuery Data vs Attr? Unable to set data attribute using jQuery Data() API Select elements by attribute in CSS