0

I'm trying to extract the FIRST data attribute from the following mark-up:

<button class="buttonMiddle" data-vid="1">
    <a href="#">who helped them</a>
</button>

<button class="buttonMiddle" data-vid="2">
    <a href="#">who helped them</a>
</button>

the JS I've conjured is:

var button1 = $('.buttonMiddle').get(0).data('vid');

console.log(button1);

Chrome's console gives me this:

Uncaught TypeError: Object # has no method 'data'

I've covered the basic troubleshooting --> jQuery is loaded before this js file, they are both loaded just before the closing body tag (so no need for $(function() {// find data-attribute});.

1
  • 2
    .get() will get you a DOM Element - if you want to use .data() you need a jQuery object because .data() is a jQuery method so using .eq() will return a jQuery object Commented May 6, 2013 at 13:08

1 Answer 1

6

Try to use eq() instead of get() here:

var button1 = $('.buttonMiddle').eq(0).data('vid');
Sign up to request clarification or add additional context in comments.

2 Comments

Perfect, thats the solution! For anyone else who comes by this, if you want to read more on @wirey's explanation check it out here --> api.jquery.com/eq
Be careful about key that must be lowercase when using $(selector).data(<lowercase param name>) no matter how defined Upper or Lower case. Or using full parameter names with original case when you use $(selector).attr(<full param name>).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.