JQUERY :Parent selector not working

2.3k views Asked by At

$(document).ready(function() {
  $(".lvl_0 ul").mouseover(function() {
    $(".subnav:parent > a span").addClass("subOpen");

  });

  $(".lvl_0 ul").mouseout(function() {

    $(".subnav:parent > a span").addClass("subOpen");

  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="tile_nav">
  <li class="lvl_0">
    <a href="#">Tile
      <span>---</span>
    </a>

    <ul class="subnav">
      <li><a href="#">XXXXX <span>---</span></a>
      </li>
      <li><a href="#">XXXXX <span>---</span></a>
      </li>
    </ul>

  </li>

  <li class="lvl_0"><a href="#">Tile</a>
  </li>
  <li class="lvl_0"><a href="#">Tile</a>
  </li>
</ul>

Please help, why this :parent selector not working with direct child. on mouse over of sub <ul> should add a class to <span> of parent <li>

5

There are 5 answers

0
Tushar On

Use parent() to get the parent element:

$(document).ready(function () {
    $(".lvl_0 ul").mouseover(function () {
        $(this).parent().children('a').addClass("subOpen");

    });

    $(".lvl_0 ul").mouseout(function () {

        $(this).parent().children('a').addClass("subOpen");
    });
});

You can also use hover

$(document).ready(function () {
    $(".lvl_0 ul").hover(function () {
        $(this).parent().children('a').addClass("subOpen");
    }, function () {
        $(this).parent().children('a').removeClass("subOpen");
    });
});
1
Arun P Johny On

In your case you are looking for the previous sibling of the ul element, also use hover/mouseenter-mouseleave events

$(document).ready(function () {
    $(".lvl_0 ul").hover(function () {
        $(this).prev('a').find('span').addClass("subOpen");
    }, function () {
        $(this).prev('a').find('span').removeClass("subOpen");
    });
});
0
Selvakumar On
To select parent in jquery you can use parent(), parents(), closest(). In which way you may like.

$(document).ready(function () {
    $(".lvl_0 ul").mouseover(function () {
        $(this).parent().children('a').find('span').addClass("subOpen");

    });

    $(".lvl_0 ul").mouseout(function () {

        $(this).parent().children('a').find('span').addClass("subOpen");
    });
});
0
stanze On

You need to select the parent of the current element by using jQuery parent method Try this fiddle

$(this).parent().addClass("subOpen");
0
Shaunak D On

Why your code does not work

:parent

Select all elements that have at least one child node (either an element or text).

You need the parent element and elements with childnodes.


So either use .closest() or .parent()

$(' > a span',$('.subnav').closest('ul')).addClass("subOpen");