Get custom attribute value in Jquery?

Miomir Dancevic picture Miomir Dancevic · Oct 29, 2014 · Viewed 11.9k times · Source

I have this html

<a data-overlay="Preparing First" href='#'>First link</a>
<a data-overlay="Preparing Second" href='#'>Second link</a>

And JS

$("[data-overlay]").click(function () {
        var text = $(this).val($(this).attr("data-overlay"));
        alert(text);
    });

When I do this, I got only OBJECT, where I got wrong?

Here is working fiddle

http://jsfiddle.net/sruq8kav/

What I need is to alert value of that custom attribute?

Answer

tymeJV picture tymeJV · Oct 29, 2014

Because you're alerting the result of .val() (and I'm not sure why you're using it) which is a jQuery object - you simply want the attribute:

var text = $(this).attr("data-overlay")
alert(text);