I've got several HTML elements with various data-attributes. I'm trying to use jQuery to store all of the data attributes for a particular element when it's clicked, then insert one of the values from that Object into another element as text. I've tried various approaches I've seen on SO, and I think I'm properly storing the data, but I can't figure out a straightforward way to pull out a particular data-attribute
value so I can insert it in the #display
element. The HTML:
<span class="source" data-spanName="spanOne" data-spanPosition="first">Span One</span>
<span class="source" data-spanName="spanTwo" data-spanPosition="second">Span Two</span>
<span class="source" data-spanName="spanThree" data-spanPosition="third">Span Three</span>
<span id="display">display attribute here</span>
The jQuery I've tried:
Attempt 1 (returns [object Object]):
$('.source').click(function () {
var rowData = $( this ).data();
$('#display').text( rowData ); //returns [object Object]
});
Attempt 2 (returns undefined):
$('.source').click(function () {
var rowData = $( this ).data();
$('#display').text( $.rowData[0].spanname ); //returns undefined
});
Attempt 3 (displays all data, but as a string):
$('.source').click(function () {
var rowData = $( this ).data();
var prettyRowData = JSON.stringify( rowData );
$('#display').text( prettyRowData ); //returns attributes, but as a string and I'd have to parse it to pull out a value
});
Desired end result:
<span id="display">spanOne</span>