Locate the ID of the element targeted by the cursor in a contenteditable field

Within a contenteditable div, I have various child elements with different ids. When the cursor is moved inside the contenteditable tag, I want to retrieve the id of the element at the cursor position.

For example:

  1. If the cursor is on the word "one," the output should be the id of that element which is 1.
  2. If the cursor is on the word "two," the output should be 2.

I have attempted to achieve this by getting the id of the parent element instead of the actual target element.

function check(e){
  console.log($(e.target).attr('id'))
  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div contentEditable="true"   id="res" tabindex="2"  onkeydown="check(event)">solve:
<span id="1">one</span>
  <p id="2">two</p>
  <i id="3">three</i>
</div>

Answer №1

Follow these steps to achieve it:

$('#res').on('keyup', function() {
  var el = window.getSelection().getRangeAt(0).commonAncestorContainer.parentNode;
  console.log(el.id);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div contentEditable="true" id="res" tabindex="2">solve:
  <span id="1" class='number'>one</span>
  <p id="2" class='number'>two</p>
  <i id="3" class='number'>three</i>
</div>

For more information on window.getSelection(), you can visit this link.

To learn about using window.getSelection() with getRangeAt(), check out this article.

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

Combining several markdown files into a unified HTML document

Is there a way to merge multiple .md files into a single HTML file? I know that Pandoc can convert .md to HTML, but I'm unsure if it's capable of converting multiple files at once. Would I need to create a program to manipulate the tool in orde ...

Leverage lodash operators within nested object properties

My data consists of an array of objects { "agent_name": "AgentName", "analytics": [ { "date": "Tue, 1 Aug 2021 00:00:00 GMT", "intents_count":[ { "coun ...

Succession of Mongoose queries

One interesting feature of my model is the ability to chain queries like find(), limit(), and skip(). However, there arises a question: How can I apply the limit or skip function to the output of Model.find() if the returning value does not inherently cont ...

In TypeScript, a mapped type is not allowed to define properties or methods

My challenge involves defining an interface with keys that match a specific enum key type. However, when I attempt to declare this type, I encounter the following error message: A mapped type may not declare properties or methods. Below is the code snip ...

Iterating through jQuery code and adjusting it as needed

Below is the code I have been working on: var flag=true; $(document).ready(function(){ $("glavna").mouseenter(function(){ if(flag) { $(".ocenjevanje").animate({right:"+=440", bottom:"+=20"},1000); $(".svetovanje ...

Issues arise when attempting to insert quotes within a JSON object for database insertion

I am currently facing an issue where I need to store a JSON object in the database to retrieve it later and manipulate it using JavaScript. However, I am encountering a problem I have never faced before. When I store the JSON object as a String and then tr ...

Scrapy and Python data gets corrupted by <br> tags causing issues

As I attempt to extract the text from Amazon reviews using scrapy, I encounter an issue. Reviews with multiple lines have their text separated by "< br >" tags within a span element. So, when I try to scrape the first review, I use this line of code: ...

The background size does not adjust to the size of the viewport

I am encountering an issue with the background size on my webpage. When changing the viewport size on this page , the background does not adjust to the new viewport dimensions immediately. It seems to retain the previous dimension and only updates to the c ...

Mastering the art of transforming JSON data for crafting an exquisite D3 area chart

I often find myself struggling with data manipulation before using D3 for existing models. My current challenge is figuring out the most efficient way to manipulate data in order to create a basic D3 area chart with a time-based x-axis. Initially, I have a ...

Conditional rendering of Materialize navbar links

I am currently working with React Materialize and React Router Dom. My goal is to display navlinks only to authenticated users using conditional rendering. However, when I implement it as shown below, the navlinks are displayed vertically instead of hori ...

Tips for making a div expand to take up the available space on the left side of a taller div

Could you take a look at the scenario below? I'm attempting to position my yellow div beneath the red div and on the left side of the lower part of the green div. When I apply clear: left, it moves down but leaves empty space above it. Is there a way ...

Implement a drop-down menu in an MVC application by utilizing jQuery

When I select a country from a dropdown, I am trying to populate the state dropdown list. The stateList function successfully filters based on the country name criteria, but when it returns to the view, it displays all states instead of the filtered result ...

Sending AngularJS data using the POST method to be retrieved in PHP's $_POST

After successfully implementing a post request from my AngularJS app to a PHP script, I am now trying to ensure that the data received in my php script is stored in the $_POST['jwt'] variable. Below is an example of my AngularJS code: var dataR ...

ExpressJS route files may potentially conflict if endpoints clash

I'm having trouble using the same endpoint in different route files. index.js: var users = require('./routes/users.js'); var orders = require('./routes/orders.js'); app.use('/users', users); app.use('/orders&apos ...

Updating values within an ng-repeat loop by using the ng-change directive to increment or decrement

Below is an example code snippet that demonstrates a checkbox feature: <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Welcome to LearnKode - A code learning platform</title> ...

Is the express-mongo-sanitize functionality up and running?

Currently, I am in the process of implementing security middleware for my modest MERN web application. Specifically, I have opted to utilize helmet and express-mongo-sanitize to safeguard against NoSQL injection attacks. In my server.js file, I have confi ...

What is the reason that the slick slider is unable to remove the class filter?

Having troubles with my slickUnfilter function, even though slickFilter is working perfectly? Here's a snippet of my HTML: <div class="slider-wrapper" id="wrapper"> <div class="post" id="post1"&g ...

Can one track the moment when a user clicks on an advertisement within a YouTube video?

Can we track when a user clicks on an advertisement within a YouTube video? We have integrated the YouTube API v2 into our website, allowing users to watch videos. The issue is that when a user clicks on an advertisement, the YouTube video pauses automat ...

The Ajax response is not showing up within the success function in jQuery Mobile

Recently, I have been working on creating a simple login form with username and password fields using jQuery Mobile. The validation for the username and password is supposed to be done through an ajax page. Surprisingly, everything was working perfectly ...

Changing URL Links to Plain Text with Regular Expressions

When sending an email from my application, I am primarily using HTML format and applying a regex to remove the HTML tags for a plain-text alternative view. (using @"<(.|\n)*?>"). My goal is to substitute the <a> hyperlink tag with a plain- ...