Reputation: 1
I'm trying to alert the data-keyid when the fullkey is clicked.
$(function() {
$('.fullkey').click( function (){
var keyId = $(this).attr('data-keyid');
alert(keyId);
});
});
<div class="fullkey">
<div data-keyid="c-key"></div>
</div>
Upvotes: 0
Views: 97
Reputation: 31
You can also try this:
$(this).data("keyid");
HTML 5 gives you the ability to add the custom data attributes where each attribute name starts with "data-". JQuery allows to access value of the attribute using the data() function.
Example: . The data() function returns the value="c-key".
Upvotes: 0
Reputation: 2060
Please find the demo here.
HTML:
<div class="fullkey">Click here
<div data-keyid="c-key"></div>
</div>
JS:
$(function() {
$('.fullkey').click(function() {
var keyId = $(this).find('div').attr('data-keyid');
alert(keyId);
});
});
Upvotes: 0
Reputation: 1194
when you click on .fullkey
then this
has the reference of .fullkey
but data-keyid
is attribute of its child element so use find
to find the element inside it and then get its attribute.
$(document).ready(function(){
$('.fullkey').click(function (){
var keyId = $(this).find('div').attr('data-keyid');
alert(keyId);
});
});
$(function() {
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<div class="fullkey" style="bgcolor:black">
<div data-keyid="c-key">Click</div>
</div>
Upvotes: 0
Reputation: 36599
Use
.find
to get the child nodes of the parent element. You can filter the set of returned elements using specific selector.$(this)
is parent selector in this example.
[data-keyid]
selector could be used to find the child node having attribute as data-keyid
Try this:
$(function() {
$('.fullkey').click(function() {
var keyId = $(this).find('[data-keyid]').attr('data-keyid');
alert(keyId);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="fullkey">
<div data-keyid="c-key">Click Here</div>
</div>
<div class="fullkey">
<div data-keyid="d-key">Click Here</div>
</div>
<div class="fullkey">
<div data-keyid="e-key">Click Here</div>
</div>
Upvotes: 1