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

JavaScript 200 code doesn't execute the success function for the post method

Hey there! I'm having an issue with sending json to a django web service. Strangely, the success function isn't triggering even though I receive a 200 status code. I've tried changing the data type to "json", "text", and "html", but still no ...

React.js router - struggles to clean up unsightly query parameters in the URL

I've been trying to eliminate the query string by following this solution: var { Router, Route, IndexRoute, IndexLink, Link } = ReactRouter; var createHashHistory = History.createHashHistory; var history = createHashHistory({queryKey: false} ...

Calculate the height of the document in Python by using the function $(document).height()

I am looking to retrieve the height of a document for different URLs, essentially creating a JavaScript function similar to $(document).height() that works across all pages. Any suggestions on how I can accomplish this task? I have experience with Python ...

Please use Shift + Enter feature only when using desktop devices

In my React chat application, I have implemented a textarea for message input to allow multiline support. This works smoothly on mobile devices as pressing Enter creates a new line and a send button is available to submit the message. However, I want a di ...

The touchstart event is activated when you touch an item within

Is it possible to retrieve the index of ul li elements with touchstart, similar to how it can be done with a click function? <ul id = "list" ontouchstart="touchStart(event,'issues')"> <li> ...

Issue with MongoDB find() function not retrieving any results (Assignment)

I am currently working on an assignment that requires the use of noSQL databases. Although I understand most of the queries we have to perform in mongoDb, every query I execute seems to return a blank result. Initially, we are required to create a collect ...

The function getComputedStyle('background-color') will return a transparent value that does not inherit from any ancestor element

When using getComputedStyle, it is expected to return the final computed CSS property value. However, for background-color, browsers tend to return "transparent" (or rgba(x,x,x,0)) instead of computing the inherited value from ancestors. The method only s ...

Alter the configuration of a JSON object

I'm currently working on modifying the following JSON text. It has the structure as shown below: { "cabecera": { "tipo_cambio": "", "fecha_emision": "", "total": "" }, "detalle": { "940b130369614bd6b687dc5b41623439": { " ...

How to execute a function in a child process using node.js?

In my node.js application, I am receiving a file through a web request and need to perform a time-consuming conversion process on it. To prevent this task from affecting the main thread's performance, I currently have it triggered by a setTimeout() ca ...

Place the division at the bottom of the screen

I'm facing an issue where I am trying to place a div at the bottom of the viewport but it's not working as expected. Here is how my current setup looks like: html <div class="parent"> <div class="bottom"> </div> </div&g ...

Saving an image in Flask and securely storing it in a local directory

I am looking to implement a functionality where I can upload an image and pass it to the Python code in Flask for local storage. While following a tutorial, I encountered an issue with the query as the request always returned 'No file part': if & ...

What is the best way to set an object's value to null in AngularJS?

Check out this code snippet var data={}; data={stdId:"101"}; data={empId:"102"}; data={deptId:"201"}; In my project, I'm receiving data from services into a data object with differing key names such as stdId or empId, etc. I need to set empty val ...

Optimizing SEO with asynchronous image loading

I've been developing a custom middleman gem that allows for asynchronous loading of images, similar to the effect seen on Medium. Everything is functioning smoothly, but I'm uncertain about the impact on SEO. The image tag in question looks like ...

Guide on selecting a radio button based on data retrieved from a MySQL database

How can I populate my radio button in an edit form with data from MySQL by writing the value in the radio button? Below is the code snippet: foreach($arrAnswer as $ans) { <input name = "answer_'.$i.'" type="radio" value="' ...

The Yeoman/Grunt-usemin is failing to update the index.html file even after adding new JavaScript code

As I work on developing a web app using Yeoman and the Angular generator on Windows 7, I go through the process of running 'yo angular' followed by 'grunt' to build the app for deployment. The index.html file in the dist folder gets upd ...

Display a loading component within the navbar in React while waiting for data to be retrieved

I recently updated my navbar component to accept dynamic values for menu titles. One of these dynamic values is the username, which needs to be fetched asynchronously. To handle this, I decided to display a loading animation until the username is fully fet ...

Selenium's XPath locator unable to locate element despite being visible on the browser

Attempting to extract the WHO coronavirus data from the left sidebar of this website: using Xpath. Here is the code snippet: from selenium import webdriver import time driver = webdriver.Firefox() driver.get("link_to_the_page") time.sleep(30) coun ...

Angular 2 signal sender

I have a specific class definition for my Project: export class Project { $key: string; file: File; name: string; title: string; cat: string; url: string; progress: number; createdAt: Date = new Date(); constructor(file: File) { th ...

Finding mongoose in an array of objects nested within another object

Here is the MongoDB JSON document I am working with: { categoryId: '1', categoryName: 'Outdoors Equipments', items: [ { itemId: '1', itemName: 'Camping T ...

The application of border-radius to a solitary side border forms a unique "crescent moon" shape rather than a traditional semi-circle

Is there a way to transform this shape into a regular semicircle, avoiding the appearance of a moon, and change the image into a circle rather than an ellipsis? http://jsfiddle.net/226tq1rb/1/ .image{ width:20%; border-radius:500%; border-rig ...