Igor O Igor O - 2 months ago 6
HTML Question

Get closest div inside clicked <li>

I'm trying to get the closest DIV inside a li item, to apply a new class:

<ul id="menu">
<li class="here">
<img src="image">
<div class="border selected"></div>
</li>
<li class="here">
<img src="image">
<div class="border"></div>
</li>
.....


I wanted to be able to click inside the li tag and apply the class 'selected' to the div that already has class border.

I was trying to use .closest and .find but I couldn't get the good result.
Is there any recommendation? Thanks!

EDIT: https://jsfiddle.net/a8pm1aj7/

Answer

.children() seems to work fine.... You may have more of an issue with CSS hierarchy. Make certain the selected class is defined after the border class in the CSS.

$(document).ready(function() {
  
  $( '.here' ).on('click', function() {
      var theDiv = $(this).children('.border');
      $('.border').not(theDiv).removeClass('selected');
     $( theDiv ).toggleClass('selected');
  });
  
  
  });
li { display: block; margin: 10px; width: 80%; }

.border { height: 20px; background: #eee; }
.selected { background: #fee; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

    <ul id="menu">
        <li class="here">
          Text/image
          <div class="border"></div>
        </li>
        <li class="here">
          Text/image
          <div class="border"></div>
        </li>
      </ul>

Updated your fiddle and fixed issues with it. - You had the div positioned absolute and set at 100% width and 100% height. S0 basically, it was the size of the window. Actually linked the jQuery library to the fiddle.