user1937021
user1937021

Reputation: 10791

:First-child affecting all children

Hi I'm trying to target the first <a> element under .current-cat-parent but my jquery code is affecting all the <a> elements underneath this. How can I just target the first immediate <a> element? Thanks!

$(".current-cat-parent a:first-child").click(function(e){
            e.preventDefault();
          if( $(this).hasClass('hide') ){
            $(this).next().slideDown(800);
            $(this).removeClass('hide');
          } else { 
            $(this).next().slideUp(800);
            $(this).addClass('hide');
          }
    });
<li class="cat-item cat-item-1 current-cat-parent">
  <a title="View all posts filed under Clothing" href="http://site.com/category/clothing">Clothing</a>
  <ul class="children">
    <li class="cat-item cat-item-3"><a title="View all posts filed under Jeans" href="http://site.com/category/clothing/jeans">Jeans</a></li>
    <li class="cat-item cat-item-2 current-cat"><a title="View all posts filed under Suits" href="http://site.com/category/clothing/suits">Suits</a></li>
  </ul>
</li>

Upvotes: 2

Views: 215

Answers (4)

Jai
Jai

Reputation: 74738

Instead of this:

$(".current-cat-parent a:first-child")

use the direct child >:

$(".current-cat-parent > a:first-child")

Note:

I think your main issue is .hide css class. Why you need it? I suggest you to make it a blank css class or remove it.

Fiddle

Upvotes: 2

Salman Arshad
Salman Arshad

Reputation: 272106

If you look at the HTML markup closely, you will notice that all a elements are also first-child of their respective parents. The solution is to use one of these selectors:

.current-cat-parent > a
.current-cat-parent a:first
.current-cat-parent a:eq(0)

Note that :first and :first-child are not the same.

Upvotes: 1

Adil
Adil

Reputation: 148120

You can use eq() to target the first child.

$(".current-cat-parent a:eq(0)")

Upvotes: 2

bipen
bipen

Reputation: 36531

it should be

$(".current-cat-parent a:eq(0)").click(function(e){

Upvotes: 1

Related Questions