简体   繁体   中英

How can I target a specific span inside a clicked div element?

I've tried a few methods to hide a span inside a div ".text-body" but can't seem to make it work. Below is one method I've tried. How do I hide the span with class "badge badge-danger-lighten" only inside the element that was clicked?

$('.text-body').click(function(e){

if($(this).children('div').hasClass('media bg-light p-2'))
{
    // do something
}
else
{
    $('div.media.bg-light.p-2').addClass('mt-1 p-2').removeClass('bg-light')
    $(e).find("span.w-25.float-right.text-right").hide(); //trying to hide span here
    $(this).children('div').addClass("media bg-light p-2");





<a href="javascript:void(0);" class="text-body"><div class="media mt-1 p-2">
  <img src="/static/assets/images/users/avatar-2.jpg" class="mr-2 rounded-circle" height="48"alt="Brandon Smith" />
  <div class="media-body">
     <h5 class="mt-0 mb-0 font-14">
        <span class="float-right text-muted font-12">4:30am</span>
        Brandon Smith
     </h5>
     <p class="mt-1 mb-0 text-muted font-14">
        <span class="w-25 float-right text-right">**<span class="badge badge-danger-lighten">3</span></span>** 
        <span class="w-75">How are you today?</span></p></div></div></a>

Just a simple illustration on how you can use find if the target elements are not a direct child/children

 $('.text-body').click(function(e){ //this will look for any element with a class badge and badge-danger-lighten $(this).find('.badge.badge-danger-lighten').hide() })
 .text-body{ border:1px solid; }
 <div class="text-body"> <span class="badge badge-danger-lighten">Target Span</span> <br> <span>Another Span</span> <div> <span class="badge badge-danger-lighten">Another Target Span/ deeply situated</span> </div> </div> <br> <br> Click the rectangle above <script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>

In your question you specify you want to hide an element with "badge badge-danger-lighten" you could simply specify that as a selector to the find method, and then call hide...

    // $(e).find("span.w-25.float-right.text-right").hide();
    $(e).find(".badge.badge-danger-lighten").hide();
    

That will select and hide all child elements with those classes.

You can read up on hide and find here https://api.jquery.com/hide/ and here https://api.jquery.com/find/

$(e).find("span.w-25.float-right.text-right").hide();

Needed to be:

$(this).find(".badge-danger-lighten").hide();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM