0

Given the following html:

<ul class="sub-categories">
    <li>
        <a href=""><img src="" alt=""></a>
        <h2 class="sub-header">
            <a href="">category name</a>
        </h2>
    </li>
</ul>

I want to add the class 'current' to the 'a' tag inside '.sub-header' irrespective of which anchor is clicked.

The following works only when I click the first anchor.

$('ul.sub-categories li a').click(function(event) {
    event.preventDefault();

    $(this).next(".sub-header").children('a').addClass("current");
});

How do I make it work irrespective of which anchor is clicked ?

5 Answers 5

2

Event delegation:

$('ul.sub-categories>li').on('click', 'a', function(event) {
  event.preventDefault();
  $(event.delegateTarget).find('h2>a').addClass("current");
});

http://jsbin.com/wajerujose/1/edit?html,css,js,output

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

Comments

0

Try this:

$('ul.sub-categories li a').click(function (event) {
    event.preventDefault();
    // works for first a clicked only        
    $(this).next(".sub-header").children('a').addClass("current");
});

2 Comments

works only for the first clicked element 'a', not for the second
@Marco So you want to add class to 'a' inside first .sub-header irrespective of which anchor is clicked?
0
$('.sub-categories li').click(function(event) {
  event.preventDefault();
  $(this).find('.sub-header a').addClass("current");
});

1 Comment

@Marco It's not probable I'd suggest you something that does not work: jsbin.com/tuqeyi/1/edit?html,css,js,output. Means you should show us more code. Or you have other listeners that are preventing the click to propagate or...
0

Try this:

$('ul.sub-categories > li > a').click(function (event) {
    event.preventDefault();       
    $(this).next(".sub-header").find('a').addClass("current");
});

Main is to change the selector to ul.sub-categories > li > a from ul.sub-categories li a. Because ul.sub-categories li a is acquiring all <a> within .sub-categories, while your target is only those <a> tags which are direct target to ul.sub-categories li.

1 Comment

works only for the first clicked element 'a', not for the second
0

I did more research on this site and kept playing around and found something that works. Im not sure if it's the most elegant solution, but it works.

$('ul.sub-categories li a').click(function(event) {
    event.preventDefault();

   if ($(this).parent().is(".sub-header")) {
        $(this).addClass("current");
    } else {
        $(this).next(".sub-header").children('a').addClass("current");
    }
});

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.