0

I have bootstrap 3 menu. And I want to add class to "dropdown" menu if usre click on "caret" ( parent menu item )

<ul id="menu-testing-menu" class="nav navbar-nav sf-js-enabled" style="touch-action: pan-y;">
    <li class="menu-item menu-item-has-children dropdown">
        <a class="sf-with-ul" data-toggle="dropdown">Home<span class="caret"></span></a>
        <ul class="dropdown-menu" style="display: none;">
            <li class="menu-item">
                <a href="#">Lorem Ipdum</a>
            </li>
            <li class="menu-item">
                <a href="#">Lorem Ipdum</a>
            </li>
            <li class="menu-item">
                <a href="#">Lorem Ipdum</a>
            </li>
        </ul>
    </li>
</ul>

So I try to use js

$('#menu-testing-menu li a .caret').click(function(e){
e.preventDefault();
$(this).find('.dropdown-menu').toggleClass('dd-menu-show');
});

but it doesn't work. How to solve thise problem?

3
  • You also need to $(this).parent().find(); as dropdown menu is not inside a Commented May 25, 2017 at 18:24
  • @abhishekkannojia incorrect, the .caret class is on the span element inside the a. Commented May 25, 2017 at 18:25
  • @ChemicalRocketeer Oh my bad! Thought it was on same line. Commented May 25, 2017 at 18:25

4 Answers 4

1

$(this).find('.dropdown-menu') is not possible when clicking .caret because $(this) is looking inside the current element and it is empty.

You might also want to consider adding the click event to the entire <a>.

Try this

$('#menu-testing-menu li a .caret').click(function(e){
  e.preventDefault();
  var parent = $(this).closest('.dropdown');
  parent.find('.dropdown-menu').toggleClass('dd-menu-show');
});
Sign up to request clarification or add additional context in comments.

Comments

0

.find() searches for a node inside the selected node. You are selecting the .caret span element, so it's trying to find a .dropdown-menu node inside that, which of course does not exist. You'll want to navigate up the tree to the .dropdown node, and then do your find() call.

Comments

0

$(this).find(".dropdown-menu") will not work because there is no element in the current clicked element with class dropdown-menu. So just try :

$('#menu-testing-menu li a .caret').click(function(e){
    e.preventDefault();
    $('.dropdown-menu').toggleClass('dd-menu-show');
});

Comments

0

You can do it in this way.

$('#menu-testing-menu li a .caret').click(function(e){
   e.preventDefault();
   $(this).parent().next('.dropdown-menu').toggleClass('dd-menu-show');
});

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.