Reputation: 1005
I'm trying to get an alert of this button's data, specifically the '6374' part. Any ideas how to grab it with jQuery?
html:
<button data-snax-post="6374">Text</button>
jquery:
alert(('.menu-item').attr('data-snax-post'));
Upvotes: 0
Views: 86
Reputation: 503
Use alert($('.menu-item').data('snax-post'));
to alert the data-snax-post attribute
Upvotes: 0
Reputation: 781255
The button needs to have the menu-item
class so you can select it that way.
You left out $
to call the jQuery function to select the item.
You can use the .data()
method to get data attributes.
alert($('.menu-item').data('snax-post'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="menu-item" data-snax-post="6374">Text</button>
But this won't work if there's more than one .menu-item
element on your page. It will get the data from the first one. If you're clicking on it, you probably want to use $(this)
.
$(".menu-item").on("click", function() {
alert($(this).data('snax-post'));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="menu-item" data-snax-post="6374">Text</button>
<button class="menu-item" data-snax-post="1234">Other Text</button>
Upvotes: 1
Reputation: 1026
you were missing $ and you don't have menu-item class in button element
<button data-snax-post="6374">Text</button>
alert($('button').attr('data-snax-post'));
Upvotes: 1