Tips for discovering the exact positions of child divs that are Nth siblings within a parent div

I have designed a new calendar interface with dynamic functionality. When the user clicks on any time slot displayed in IMAGE1, a span element is created dynamically to represent 8 hours starting from that clicked time.

My question is, how can I access the position of the 8th sibling div associated with the clicked time slot?

If there are alternative methods or suggestions, please feel free to advise.

$(this).nextAll().eq(7).attr("id");

IMAGE1 https://i.stack.imgur.com/KYiRE.png

The table design code below is generated when the Ajax function returns successfully:

$(r.emp_nm).each(function (index) {
                tabelBody += "<tr><td style='width:10%'><div class='col-xs-3 col-md-3 on-break-tab'>" + this.fname.charAt(0) + this.lname.charAt(0) + "</div>" + this.fname + ' ' + this.lname + " </td>";
                for (var i = 0; i < 24; i++) {
                    var tabelsubBody = "";
                    var p = 15;
                    var t_id = r.hours[i];
                    for (var j = 0; j < 4; j++) {
                        tabelsubBody += "<div style='float:left; width:25%;height:inherit;'  class='Dropablesub_td' data-employeID='" + this.id + "' data-date='" + t_id + "' id='" + t_id + "_" + this.id + "_" + j + "'></div>";
                    }
                    if (i === 23) {
                        tabelBody += "<td style='width:12.5%' class='Dropabletd' data-employeID='" + this.id + "' data-date='" + t_id + "' id='" + t_id + "_" + this.id + "'>" + tabelsubBody + "</td></tr>";
                    } else {
                        tabelBody += "<td style='width:12.5%' class='Dropabletd'  data-employeID='" + this.id + "' data-date='" + t_id + "' id='" + t_id + "_" + this.id + "'>" + tabelsubBody + "</td>";
                    }
                }

            });
            $("#tabelBody").html(tabelBody);
            $("#tdDate").html(r.today);
            $("#SelectDate").val(r.today);
            $("#currentSelect").val("Days");

            Events();

Here's the function for the event handling:

 function Events() {

    $("body").on("click", ".Dropablesub_td", function () {
        var hidid = $(this).attr("id");
        var Myleft = $(this).position().left;
        var Mytop = $(this).position().top;
        alert($(this).nextAll().eq(7).attr("id"));
        $(this).append("<span id='" + hidid + "'  class='divId label label-success ui-widget-content filediv unselectable' >ABCDEFGHIJKLMNOPQRSTUVWXYZ<span>");
        $(this).children(
                ).css({zIndex: 999, position: "absolute", top: Mytop, left: Myleft, width: '40%', display: "block", border: "#808080 solid 2px", color: "black", background: "#00CEB4"});
    });
}

Answer №1

To retrieve the desired element, you can utilize the .index() method of the current element and then use .eq() to select the following element.

Below is a snippet where I've simulated pseudo code for illustration:


$(document).on("click", ".dropabletd", function() {
  var tr = $(this).closest('tr');
  var tds = tr.find('td');
  var index = tds.index(this);
  var sibling = tds.eq(index + 8);
  console.log($(this).attr('id'), sibling.attr('id'));
});

createTable();

function createTable() {
  var tableBody = ""
  for (var i = 0; i <= 23; i++) {
    tableBody += "<td class='dropabletd' id='id" + i + "'>" + i + "</td>";
  }
  $("table tr").html(tableBody);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr></tr>
</table>

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

Unleashing the Power: Crafting Impeccable For Loops

After running the select query in the "get-employee.php" page, I obtained the answer for this page. Then, I returned the data to the previous page (home.php). On this page, I added a for loop in JavaScript before the tag with the class "col-md-3". Within t ...

How to make Jquery skip over elements with a particular data attribute

I am looking to select all elements that are labeled with the 'tag' class. Once these items have been selected, I would like to remove any items from the list that contain the attribute 'data-tag-cat'. var tags = $('.tag'); c ...

React Component is not functioning with the timer running

I am currently developing a basic timer app using React. Here is the code snippet I have so far: import React from "react" const timer = (props) => { let time = 25; let processStatus = props.timerProcessStatus; // set to true if(processSta ...

remove item from list of objects

Currently, I am actively using vuejs 3 in conjunction with laravel. This is the object array that I am currently working with: [[Target]] : Array(3) 0: Proxy(Object) {id: '96', name: 'DESINCRUSTADOR DCALUXE - HIDROCAL ELECTRONICO', cat ...

How can we best organize a VueJS application to accommodate this specific logic?

I am currently working on an app that needs to display data fetched from multiple sources based on a condition. The issue I am facing is that the process of fetching, organizing, and returning the data varies depending on the source, sometimes even requiri ...

Use PHP to create a new JSON file on the server by submitting a form, then utilize a second form to update

My current goal is to create a json file using a form and then update that file with another form. Both of these processes are handled in the process.php file. I have managed to successfully update the json file if it is named as data.json initially in pro ...

What is the mechanism by which Redux sends state to mapStateToProps?

I'm currently delving into the inner workings of React and Redux, and recently came across FuelSavingsPage.js in this sample project. While I grasp how actions is obtained in mapDispatchToProps, I am uncertain about how state is passed to mapStateToPr ...

Detach attention from TextField select component in Material UI and React through manual means

When I create a select input using the TextField component from Material-UI library, I need to manually remove focus after an option is selected. I attempted to achieve this by using a reference to the TextField with the 'inputRef' prop. However, ...

The JavaScript code is not executing properly within the HTML document

I am trying to execute a function from my JavaScript file in my HTML page. Here is the code snippet: index.html <!DOCTYPE html> <html><body> <h2>Web1</h2> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jq ...

How to Trigger a Child Component Function from a Parent Component in React.js

I want to trigger a function in my child component when a button is clicked in the parent component. Parent Component: class Parent extends Component{ constructor(props){ super(props); this.state = { //.. } } ...

Developing Reactive Selections with Material-UI is made easy

After spending about 5 hours on a task that I thought would only take 15 minutes, I still can't figure out the solution. The issue is with my React App where I have two dropdowns in the Diagnosis Component for users to select Make and Model of their a ...

Forcing a property binding update in Angular 2

Take a look at this particular component import {Component} from 'angular2/core' @Component({ selector: 'my-app', providers: [], template: ` <div> <h3>Input with two decimals</h3> <input type ...

Identifying the differences between a select2 dropdown and select2 multiselect: a guide

I currently have two different controls on my page: a select2 dropdown and a jquery multi value select Select2 Dropdown <select id="drp_me" class="select2-offscreen"> <option value="1">one</option> <option value="2">two</op ...

I am experiencing issues with the detection of mouseover events on an SVG circle

I am currently working on a d3 map with zoom functionality that displays circles representing different cities. However, I am facing an issue where the mouseover event for the circles (which shows tooltips and clicking reveals some lines) seems to only reg ...

Getting just the main nodes from Firebase using Angularfire

I'm having trouble figuring out how to print just the parent element names from the structure of my database. The image provided shows the layout, but I can't seem to isolate the parent elements successfully. ...

Is there a way to automate the duplication/copying of files using JavaScript?

I have a GIF file stored in the "assets" directory on my computer. I want to create multiple duplicates of this file within the same directory, each with a unique filename. For example: If there is a GIF file named "0.gif" in the assets directory, I woul ...

What is the best way to convert minutes into both hours and seconds using javascript?

In order to achieve this functionality, I am trying to implement a pop-up text box where the user can choose either h for hours or s for seconds. Once they make their selection, another pop-up will display the answer. However, I am facing issues with gett ...

Steps to display a video using a Jupyter widget in a Jupyter Notebook

Imagine I have a directory containing 4 video files (such as "movie1.mp4", "movie2.mp4" and so on). I aim to utilize ipywidgets to enable the user to choose which video they want to watch. Here's an example: import ipywidgets as wd from IPython.disp ...

Requires a minimum of two page refreshes to successfully load

Our website is currently hosted on Firebase. However, there seems to be an issue as we have to refresh the website at least twice in order for it to load when visiting www.website.com. Update: We are unsure of what could be causing this problem. W ...

Is PHP loaded prior to the `html body`?

I'm facing a unique challenge where I am currently transferring variables from a PHP page to hidden HTML inputs. The values are extracted from these hidden inputs using a JavaScript function that is called in the following manner: <body onload=" ...