2

How do I get the data-attr of the SELECTED a using jquery when the click handler is bound to it's outer div?

<ul class="js-click">
  <li><a href="" data-attr="hello">Hello</a></li>
  <li><a href="" data-attr="world">World</a></li>
</ul>


$('.js-click').on('click', function(e) {

});

The restriction here is that I have to bind the click on the <ul>

3 Answers 3

1

You can do it like this:

$('.js-click').on('click','a', function(e) {
 var data=$(this).data('attr');
}); 

Listen for click on anchor

Sign up to request clarification or add additional context in comments.

Comments

1

You can access the target <a> with e.target from the click event

$('.js-click').on('click', 'a', function(e) {
    var data = $(e.target).data("attr");
});

1 Comment

i would suggest checking for the target to make sure it is an anchor tag, else the answer would be fine
0
//this would bind a handler that would execute anytime the ul is clicked
$('.js-click').on('click', function(e) { });

You're asking two questions. How to bind a handler, and then how to access the data attribute.

Binding the handler

You're close to binding the handler to your js-click class, but you can get more granular by adding a filter.

Refer to the jQuery docs for more info.

$('.js-click').on([event], [filter], [handler]);

//Bind a handler to js-click, but only execute for <a> elements
$('.js-click').on('click', 'a', function(e) { });

Accessing that data attribute

By including the data- prefix on the attribute, you're telling jQuery to cache the value automatically when it's ready.
Refer to jQuery data docs for more info

<a href="" data-attr="hello">Hello</a>

would be equivalent to

$('a').data('attr', 'hello');

To access the data, you just need to use the key, which in this case would be attr. It's worth noting that you could access the attribute directly, but use one or the other (preferably .data).

e.g. with your markup.. <a href="" data-attr="hello">Hello</a>

$('.js-click').on('click', 'a', function(e) { 
    var $this = $(this);
    $this.data('attr', 'I changed');
    //what will the value be?  It's going to be 'Hello', because we're accessing the attribute in the DOM
    alert($this.attr('data-attr'));

    //what will the value be?  It's going to be 'I changed', because we're accessing the data cache
    alert($this.data('attr'));
});

Put them together and you can do this.

$('.js-click').on('click', 'a', function(e) {
    var data = $(this).data('attr');

    //quick sanity check to make sure the attribute exists
    if(typeof data !== 'undefined') {
        //do stuff
    }
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.