Search code examples
javascriptmootools

Why isn't the data-id being selected by my function?


I am trying to get the data id to be shown in an alert menu when the user clicks on a link. But instead of the number I am getting 0 for each link.

Here is a JSFiddle of the issue

JS

$$('.postItem').addEvent('click', function(){
  var id = $('data-id');
    alert(+id);
});

HTML

<a class="postItem" data-id="9" href="#">Number Nine</a>

I have also tried using $$ to select the data-id but this didn't work either.


Solution

  • Mootools $ is converting element to mootools Element by it's id. so in your case you used it wrong, data-id in your case is an attribute so you can use the getAttribute function:

    http://jsfiddle.net/SGU8E/6/

    $$('.postItem').addEvent('click', function(e){
        var el = e.target;
        var id = el.getAttribute('data-id');
        alert(id);
    });