1

I have the following code in my HTML file.

In the JavaScript file I am trying to detect a click on any item which has the class dropdown-item ml-2 associated with it. However, the click() function is not getting caught.

$(document).ready(function() {
  $('.dropdown-item ml-2').click(function() {
    alert('hello');
  });
});
<span class="dropdown-item-text font-weight-bold">People</span>
<a class="dropdown-item ml-2" id="optAffiliates" href="#">Affiliates</a>
<a class="dropdown-item ml-2" id="optBusiness" href="#">Business</a>
<a class="dropdown-item ml-2" href="#">Inquiries</a>
<a class="dropdown-item ml-2" href="#">Students</a>
<a class="dropdown-item ml-2" href="#">Students</a>
</span>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js">
</script>

<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>

<script src="{{url('myproject/public/js/ya-jquery.js')}}" type="text/javascript"></script>

2
  • 1
    Your HTML is invalid and it looks like you are loading jQuery TWICE Commented Dec 24, 2020 at 14:23
  • i just copied the relevant part from the html file. Please let me know if i need top copy the entire file Commented Dec 24, 2020 at 14:27

2 Answers 2

2
$('.dropdown-item ml-2')

would select <ml-2> elements inside other elements that have a css class of dropdown-item. Your code has no <ml-2> elements, instead ml-2 exists as an additional css class.

What you want instead:

$('.dropdown-item.ml-2')

If you want to select items that have more than one specific css class, you write them without any spaces in between and just connect them with the class selector .

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

Comments

1

Your selector is missing a . before ml-2 and it should be

$('.dropdown-item.ml-2')

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.