简体   繁体   中英

how to close parent div with javascript jquery

I have this code and when click on close icon, the div echomessage in which the close icon, should disappear , but all divs with class echomessage disappear now.
So it should close only the div in which close button is part of

<div class="alert alert-success echomessage" role="alert">
   <span class="closebtn"><i class="fas fa-times echoclose"></i></span>  
   <?php echo 'Upload successful: <b>'.$_FILES["file"]["name"].'</b>'; ?>
</div>

$('.closebtn').click(function(){
        $(".echomessage").fadeOut(300);
    });

在关闭按钮的父元素中找到带有echomessage的div。

$(this).parent('.echomessage').fadeOut(300)

Access the parent with the class .echomessage retrieving the current one through $(this) :

 $('.closebtn').click(function(){ $(this).parent(".echomessage").fadeOut(300); }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="alert alert-success echomessage" role="alert"> <span class="closebtn">X</span> </div> <div class="alert alert-success echomessage" role="alert"> <span class="closebtn">X</span> </div> <div class="alert alert-success echomessage" role="alert"> <span class="closebtn">X</span> </div> 

If you're interested in a pure JavaScript approach , you can use the querySelectorAll() method to retrieve all the closebtn elements, follow up by the forEach() method to retrieve and add a click listener to each closebtn element and finally the parentElement property to either remove or hide the parent element of the child closebtn element.

You can check out the Code Snippet below for a practical example of what I described above:

 /* JavaScript */ document.querySelectorAll(".closebtn").forEach(btn => { btn.addEventListener("click", function(){this.parentElement.style.display ="none"}) }) 
 <!-- HTML --> <div class="alert alert-success echomessage" role="alert"> <span class="closebtn">X</span> <p>PHP CODE HERE</p> </div> <div class="alert alert-success echomessage" role="alert"> <span class="closebtn">X</span> <p>PHP CODE HERE</p> </div> <div class="alert alert-success echomessage" role="alert"> <span class="closebtn">X</span> <p>PHP CODE HERE</p> </div> 

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