Reputation: 2003
I want to call a class within jquery.
<nav class="small-nav">
<ul>
<li><a href="#">Home</a></li> </ul>
</nav> <!-- End of small-nav -->
<script>$('.handle').on('click', function()
{$('nav .small-nav ul').toggleClass('open');
});
</script>
However this doesn't work. I've tried replacing as
$('small-nav ul') or $('.small-nav ul') or $("nav '.small-nav' ul")
or $('nav.small-nav ul')
and it doesn't seem to work.
I know the code is fine because when I remove the class from the nav and when I call just the nav ul as shown below, it works.
<nav>
<li><a href="#">Home</a></li>
</nav>
<script>$('.handle').on('click', function()
{$('nav ul').toggleClass('open');
});
</script>
So can someone please tell me how I can call the specific class? Or is it not working because I am trying to call a class within another class (open) ? How do I fix it so that I can call that particular nav class and not all nav in my website.
Thanks for reading.
Upvotes: 0
Views: 168
Reputation: 82241
Your first solution didnt worked because you have wrong selector for targetting nav
with class small-nav
. also ensure that events are attached when dom isready.You need to use:
<script>
$(function(){
$('.handle').on('click', function(){
$('nav.small-nav ul').toggleClass('open');
});
});
Upvotes: 0
Reputation: 2276
Try with find();
like this
<script>
$(document).ready(function(){
$('.handle').on('click', function(){
$('nav.small-nav').find('ul').toggleClass('open');
});
})
</script>
Upvotes: 1
Reputation: 337626
Your jQuery does not work because you are looking for the .small-nav
element inside the nav
(nav .small-nav
), not a .nav
element which has that class (nav.small-nav
). Try this:
<nav class="small-nav">
<ul>
<li><a href="#">Home</a></li>
</ul>
</nav>
<script type="text/javascript">
$('.handle').on('click', function() {
$('nav.small-nav ul').toggleClass('open');
});
</script>
This code is obviously assuming that you have an element with the class handle
in your code - as it is not shown in your OP example.
Upvotes: 0