I read this discussion jQuery Data vs Attr? about the difference in usage between $ .data and $ .attr
One of the answers said this
Data set with attr()
- accessible from $(element).attr('data-name')
- accessible from element.getAttribute('data-name'),
- if the value was in the form of data-name also accessible from $(element).data(name) and element.dataset['name'] and element.dataset.name
- visible on the element upon inspection
- cannot be objects
I tried to set a value with attr() and then take it with both attr() and date(), but the result is different from what is written.
$(document).on('change', '#sl', function() {
var selVal = $(this).val();
$('#txt').removeAttr('data-name');
$('#txt').attr('data-name', selVal);
console.log("get by attr " + $('#txt').attr('data-name'));
console.log("get by data " + $('#txt').data('name')); // get only the first attribute you set
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="sl">
<option value="foo">foo</option>
<option value="bar">bar</option>
</select>
<input id="txt">
Can you explain to me if I'm wrong or if I understand what was written?
Thank you