Using Jquery's closest technique to target a class located outside of the parent div

I am having trouble accessing a class outside of its parent div

$(document).on('click', '.delete_photo', function(event){
  var del_id = $(this).attr('id');
  $.ajax({
    type:'POST',
    cache: false,
    url:'delete-photo.php',
    data:'delete_id='+del_id,
    beforeSend:function(){
       $(event.target).closest('.photo-over').show();
    },
    success:function(data) {
      $('.editor-photo').load(document.URL + ' .editor-photo-list');
    }
 });

});

Below is the HTML:

<div class="row editor-photo-list">
   {foreach from=$row item=$image_file}
      <div class="col-md-4" style="margin-bottom: 20px;">

         <div class="photo-list">
               <input id="{$image_file.id}" type='image' src='http://demo1.demaxglobal.com/content/uploads/editor-images/{$image_file.path}' value='Edit photo' onclick="return launchEditor('{$image_file.id}', 'http://demo1.demaxglobal.com/content/uploads/editor-images/{$image_file.path}');">

               <div class="photo-over">
                   <div class="line"></div>    
                   <div class="line"></div>    
                   <div class="line"></div>    
                   <div class="line"></div>    
              </div> 
           </div>

           <div class="col-md-12 photo-edit-option">                                                  
               <div class="col-md-4 photo-btn">
                   <div id="{$image_file.path}" class="delete_photo"><img src="../content/themes/default/images/close-button.png">
                   </div>
               </div>
               <div class="col-md-4 photo-btn">
                  <input id="{$image_file.id}" type='image' src='../content/themes/default/images/photo-edit.png' value='Edit photo' onclick="return launchEditor('{$image_file.id}', 'http://demo1.demaxglobal.com/conten/uploads/editor-images/{$image_file.path}');">
               </div>
               <div class="col-md-4 photo-btn">
                    <div class="post_photo-submit" id="{$image_file.path}">
                        <img src="../content/themes/default/images/the-flash.png">
                    </div>
               </div>


    </div>
</div>
{/foreach}

 </div>

Code Updated. Hopefully this provides additional insight.

I am looking to display the div photo-over when the div delete-photo is clicked. I have tried using jQuery's parent() and find() methods, but they haven't worked for me.

There are multiple divs with the same class name. When I remove the closest method, the photo-over div appears on all the DIVs.

Thank you

Answer №1

To enhance this line of code, I suggest including a functional class that acts as the container for each item. This corresponds to line 5 in your provided example:

<div class="col-md-4 product-container" style="margin-bottom: 20px;">

Once you have added this class, you can then access it in your callbacks using the following syntax:

$(event.target).parents('.product-container').find('.image-list').find('.image-overlay').show()

In the future, remember to make it easier for others to assist you by providing runnable code snippets on platforms like JSFiddle or CodePen. For more details, please refer to this helpful resource.

Answer №2

If you have the location details, you can achieve this using vanilla JavaScript, ensuring correct pathing:

Array.from(document.querySelectorAll(".delete_photo")).map(el => {
  el.onclick = e => {
    const phOver = el.parentElement.previousSibling.querySelector('.photo-over')
    // send your Ajax request and then execute `$(phOver).show()`
  }
})

When using jQuery, the process should be simplified to:

$(".delete_photo").click(function(e) {
  const sec = $(this).parent().prev()
  // make your Ajax request, followed by `$(".photo-over", sec).show()`
})

Answer №3

To find the necessary .photo-over element, you will need to use a combination of the parent(), prev(), and find() methods.

The code snippet

$(event.target).parent().parent().prev().find('.photo-over')
is used to navigate to the directly preceding .photo-over element.

Here is an example that should help:

$(document).on('click', '.delete_photo', function(event) {
  var del_id = $(this).attr('id');
  $.ajax({
    type: 'POST',
    cache: false,
    url: 'delete-photo.php',
    data: 'delete_id=' + del_id,
    beforeSend: function() {
      $(event.target).parent().parent().prev().find('.photo-over').show();
    },
    success: function(data) {
      $('.editor-photo').load(document.URL + ' .editor-photo-list');
    }
  });
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

guide on implementing a horizontal scrolling/swipe navbar with Cordova

Currently, I am working on creating a "category list" with multiple items for a Cordova app. The initial approach was to use a simple HTML list, but unfortunately, it seems that my list is causing some unexpected behavior. Desired swipe navbar layout: ht ...

Is it possible for the req.url path in expressjs to represent a different URL?

Recently, I discovered some suspicious requests being sent to my node-express server. In response, I created a middleware to record the request URLs. After logging these requests, I noticed that most of them started with '/', but there were also ...

Is it possible to implement CSS code from a server request into a React application?

With a single React app that hosts numerous customer websites which can be customized in various ways, I want to enable users to apply their own CSS code to their respective sites. Since users typically don't switch directly between websites, applying ...

Having trouble running classes using Maven test with the Testng.xml file in the terminal, however, it runs smoothly in Eclipse

While I have been successful in running my solution through the testng suit in the Eclipse console, I am facing difficulties executing the testng.xml file via Maven integrated with Sauce Labs in the terminal. Output received on the terminal: ------------ ...

Looking for assistance with implementing touch gestures on an HTML website?

I am in the process of developing a web application, and I have implemented a menu bar that shifts when a user clicks on an arrow. Each click activates a new menu option. Currently, I am looking to provide users with the ability to swipe over the screen t ...

Exploring the combined application of the AND and OR operators in JavaScript programming

{Object.keys(groupByMonthApplicants).map((obj,i) => <div key={obj} style={(i > 0 && (this.state.selectedTabId !== 'rejected' || this.state.selectedTabId !== 'approved')) ? {paddingTop:'15px',background:&a ...

Unveiling the information retrieved from an AJAX request during page load

I've been working on a unique concept for my website. Instead of displaying data from a JSON file upon load, I want it to render only when a specific click event occurs. Initially, I tried using callbacks but soon realized the flaws in that approach. ...

Browserify is unable to locate the 'jquery' module

While attempting to package my app with browserify, I encountered the following error message: Cannot find module 'jquery' from '/home/test/node_modules/backbone' I have searched for solutions to this issue, but none of them seem to ...

MVC.NET: Offering User-Friendly Loading of Initial x Items with an Option to Load More

What would be the optimal approach to efficiently load only the initial 25 elements from an IEnumerable within an ASP.NET MVC Index view? Upon employing scaffolding, a controller and views have been constructed. Within the index page, there is a creation ...

Implementing the Upload Feature using AngularJS

Currently, I'm facing a challenge in implementing an upload button on my webpage using AngularJS and Bootstrap. Specifically, I am having trouble assigning the (upload) function to that button in AngularJS. The goal is for the button to enable users t ...

`Proliferating values through constantly changing addition`

I am facing an issue with my code that involves 3 input fields: <div class="row"> <input onblur="calc_basic_amount();" id="rate_basic"></input> <input onblur="calc_basic_amount();" id="qty_b ...

Generating an interactive table using JSON with Angular 5

Can a dynamic table with dynamic columns be created based on a JSON object using Angular 5? If yes, how? The API response includes the following JSON: { "ResponseStatus": true, "ResponseData": [ { "Parent": "Company 1", ...

Issues with parsing application/json data in NodeJS using Express

As a newcomer to setting up a NodeJS express JSON REST API, I am encountering challenges in retrieving the JSON data from both GET and POST requests. Here is the code snippet that I am currently working with: var bodyParser = require("body-parser"); con ...

Tips for implementing resizable Material-UI Dialogs

I'm working on a project that involves creating a dialog box that can be resized and dragged. While I found steps in the Material-UI Dialog documentation on how to make it draggable, I'm still looking for information on how to make it resizable. ...

When the state of the grandparent component is updated, the React list element vanishes in the grandchild component. Caution: It is important for each child in a list to have a unique

In my development project, I've crafted a functional component that is part of the sidebar. This component consists of 3 unique elements. ProductFilters - serves as the primary list component, fetching potential data filters from the server and offer ...

The addition of a cancel swipe feature to an HTML5 eBook is causing the text input field for note-taking to malfunction

I am currently working on the development of a process to create HTML5 based eBooks for both desktop and mobile use using Adobe InDesign and exporting them with a plugin called In5. This plugin allows for the incorporation of html, css, and javascript duri ...

Error handling: Encountered unexpected issues while parsing templates in Angular 2

I'm a beginner with Angular 2 and I'm attempting to create a simple module, but encountering an error. app.component.html import { Component } from '@angular/core'; import { Timer } from '../app/modules/timer'; @Component({ ...

Display a PDF document within a div using jQuery or AngularJS

How can I display a pdf file inside a div using jQuery/AngularJs? For example: $.get('/helper/test.pdf', function(data){ $("#div1").html(data); // want to show the pdf in this div }); Or with AngularJs: $http({ meth ...

passport.authenticate method fails due to empty username and password values

I seem to be making a simple mistake while following a tutorial. Even though I believe I have followed all the steps correctly, when I submit the login form, I get redirected to the "failureRedirect" page. When I checked the source code in the passport mod ...

How can you make the contents of a <DIV> expand?

Picture a scenario where I have a navigation bar in the header of my web page, consisting of several links. What I want is for these links to expand horizontally to fill the parent container without me having to hard-code based on the number of links. In o ...