0

I'm having trouble figuring out how to toggle a class depending on the anchor text that is clicked.

<div>
<a id="Menu1" href="#">Menu</a>
<div id="subMenu1" class="subLevel">
<p>stuff</p>
</div>

<div>
<a id="Menu2" href="#">Menu</a>
<div id="subMenu2" class="subLevel">
<p>stuff</p>
</div>

<div>
<a id="Menu3" href="#">Menu</a>
<div id="subMenu3" class="subLevel">
<p>stuff</p>
</div>

<script>
     $(document).ready(function () {

         $("#Menu" + [i]).on('click', function (e) {
             e.preventDefault();
             $("#subMenu" + [i]).toggleClass('dropDownShow');
         });
     });
</script>

Having trouble figuring out where var i changes from number 1 - 3 depenidng on anchor link that is clicked

2
  • You're missing three </div> tags. Commented May 18, 2016 at 16:19
  • Voting to close since this question was caused by a simple typographical error. Commented May 18, 2016 at 17:00

1 Answer 1

3

Here is one way to do it:

<div>
    <a id="Menu1" class="menu" href="#">Menu</a>
    <div id="subMenu1" class="subLevel">
    <p>stuff</p>
    </div>

    <div>
    <a id="Menu2" class="menu" href="#">Menu</a>
    <div id="subMenu2" class="subLevel">
    <p>stuff</p>
    </div>

    <div>
    <a id="Menu3" class="menu" href="#">Menu</a>
    <div id="subMenu3" class="subLevel">
    <p>stuff</p>
    </div>

    <script>
             $(document).ready(function () {

                 $(".menu").on('click', function (e) {
                     e.preventDefault();
                     $(this).next().toggleClass('dropDownShow');
                 });
             });


        </script>
Sign up to request clarification or add additional context in comments.

5 Comments

Removed the use of 'better'.
thanks @NikhileshKV, what worked was using .children() instead of next()
Glad to help! But have you changed your html structure ? It should be next() according to your code.
yeah, I looked over it again and made some changes to work best for my needs.
alright. Cool. You can accept the answer if its useful. ;)

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.