0

I have the following list:

<ul class="nav nav-pills nav-pills-warning nav-pills-icons justify-content-center" role="tablist">
    <li class="nav-item">
        <a class="nav-link" data-toggle="tab" data-role-slug="admin" href="#" "="" role="tablist">
            <i class="material-icons">supervisor_account</i> Admins                   
        </a>
    </li>
    <li class="nav-item">
        <a class="nav-link active show" data-toggle="tab" data-role-slug="operator" href="#" role="tablist">
            <i class="material-icons">person</i> Operators                   
        </a>
    </li>
</ul>

I need to get the attribute data-role-slug I actually get the value in the following way:

$('a[data-role-slug]').on('click', function (e) {
    let roleSlug = $(e.target).data('role-slug');
    console.log(roleSlug);
});

the method works well, the only problem happen when the user click on the <i> tag inside the <a> tag, in that case the roleSlug will be undefined.

Is there a way to handle this issue without hard code?

2 Answers 2

2

Just use this inside the event handler. It will be the <a> instance the event occurred on regardless of what child is targeted

Or alternatively e.currentTarget will return the same instance as well

$('a[data-role-slug]').on('click', function (e) {
    let roleSlug = $(this).data('role-slug');
             // OR $(e.currentTarget).data('role-slug');
    console.log(roleSlug);
});
Sign up to request clarification or add additional context in comments.

Comments

-1

That's because the target of an event is the element that actually received it, not the one is bubbled up to.

However you can try to be sneaky, maybe try something like this ?

$('a[data-role-slug]').each((index, element) => {
    element.on('click', () => {
        let roleSlug = element.data('role-slug');
        console.log(roleSlug);
    });
});

Alternatively you can use the .parent method to find the right element

$('a[data-role-slug]').on('click', function (e) {
    let roleSlug = $(e.target).data('role-slug');
    if (!roleSlug) {
        roleSlug = $(e.target).parent('a[data-role-slug]').data('role-slug');
    }
    console.log(roleSlug);
});

3 Comments

is there a way to avoid iteration?
Made an edit to suggest another solution not using iterations
Over complicating a simple and very common situation

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.