Steps to add an element following the caret's current position in the document

Initially, I assumed this task would be straightforward using Javascript. However, I quickly realized my mistake: Within the TinyMCE iframe body, I have the following HTML code:

   <ul>
      <li><a href="#">First</a></li>
      <li><a href="#">Second</a></li>
      <li><a href="#">Third</a></li>
   </ul>

My goal is to place the cursor after the word "Second" and upon clicking a button, trigger an onclick-function that inserts a new "LI" element AFTER the "Second" list item, resulting in the following updated structure:

   <ul>
      <li><a href="#">First</a></li>
      <li><a href="#">Second</a></li>
      <li><a href="#">New inserted list item</a></li>
      <li><a href="#">Third</a></li>
   </ul>

It's worth noting that the LI-tags do not have any ID or class assigned to them, ruling out the use of getElementById. This limitation is where I encounter difficulties. (Furthermore, this functionality takes place within a TinyMCE editor textarea, though this detail shouldn't impact the overall approach.)

Answer №1

Check out the live demo by clicking here.

var links = document.querySelectorAll('ul li a');
console.log(links);

for (var j=0; j<links.length; ++j) {
  links[j].addEventListener('click', createList);
}

function createList(event) {
  var listItem = document.createElement('li');
  var newLink = document.createElement('a');
  newLink.href = '#';
  newLink.textContent = 'Click me!';
  newLink.addEventListener('click', createList);
  listItem.appendChild(newLink);
  event.target.parentNode.insertBefore(listItem, event.target.nextSibling);
}

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

Update the object with fresh data once the XML data is transformed into JSON format

I am currently converting XML attributes into JSON format. Below is the complete function that I will explain step by step: request.execute('[someSP].[spSomeSP]', function(err, dataset) { if (err) { reject(err); } ...

What could be causing the failure of loading CSS images or JS in my Laravel project?

This is a continuation of my previous question where I managed to get the site up and running. Initially, all files including css, js, and images were loading properly. However, now I am encountering issues as the files are not loading and the console disp ...

Can you show me how to recreate a 502 gateway timeout error?

Looking for suggestions on how to create a page that exceeds 600 seconds to load? Any tips on triggering a 502 gateway timeout error would be helpful as well. ...

Modify the layout of the date selector to display weekdays instead - material ui

How can I change the datepicker format to display weekdays (Monday, Tuesday,..) instead of MM/dd/yyyy? Currently, the datepicker is set up with the format format="MM/dd/yyyy". Would it be possible to modify this? Here is the source code: <MuiPickers ...

Mastering data extraction from JSON using React JS (with Axios)

Being new to ReactJS and axios, I am facing a challenge. I need to iterate through JSON data and extract values where the key is a number (e.g. 0, 1, 2...). However, I am unsure how to implement this in my code since the server provides dynamic JSON data ...

Effortlessly uploading large files using axios

I am currently facing an issue and I am seeking assistance. My goal is to implement file chunk upload using axios, where each chunk is sent to the server sequentially. However, the requests are not being sent in order as expected. Below is a snippet of m ...

The dynamic countdown timer is malfunctioning as the clock is inaccurately displaying the current time

When I refresh the page, my JavaScript flipclock starts from the beginning. I want it to resume from where it was last stopped before the page refresh. Additionally, I need the timer to stop every day at either 4:00 AM or 4:00 PM. However, when I try to in ...

What is the best way to transfer data from a fully filled out JSON form to a PHP database

Is there a way to automatically send a completed JSON form when the device detects an internet connection? I am facing the challenge of dynamically generated IDs for each question and need to figure out how to submit the data to the database on button cl ...

Is there a way to execute a function only once when the submit button is clicked in a jQuery AJAX form?

I am using Django to create a website where users can create groups. To allow users to fill in group information and upload an image as the group logo, I have implemented an HTML form. In order to preview the logo before submission, I have used AJAX to upl ...

What could be causing the player to take damage when either the bullet disappears or when they are hit?

I've encountered a problem with my code where bullets causing damage to the player even after despawning or hitting an edge. It's difficult to troubleshoot since the damage is applied passively, making it challenging to isolate specific collision ...

Accessing JSON data from a URL for use within a specific context

I am currently utilizing the request module within Express to fetch a JSON file from a specified link. var url = 'https://api.github.com/users/google/repos'; request.get({ url: url, json: true, headers: {'User-Agent': &apo ...

Unable to obtain a response even after providing the correct API key in a Node.js POST request

Can you please assist me in troubleshooting the POST request code below? Here is a snippet of the code: const express = require("express"); const bodyParser = require("body-parser"); //const request = require("request"); const https = require("https"); c ...

I'm wondering why this isn't working properly and not displaying the closing form tag

What could be the reason for this not functioning properly? The tag appears to close on its own and the closed tag is not being displayed. As a result, the if(isset($_POST['payoneer-btn'])) statement is not triggering. https://i.stack.imgur.com/ ...

Retrieving the text of a button using Protractor

After developing a unique locator to identify an element utilizing the ng-click method, I was able to retrieve a button reference from my Document Object Model (DOM). this.button = element(by.ngClick('login()')); Now, my goal is to extract the ...

Unpacking the mystery of the cdvfile:// protocol

I am currently working on a Cordova App and I am using <img class="profile-thumbnail" src="cdvfile://localhost/persistent/Photo/mypicture.jpg"> to display content in the view. However, when I generate a new mypicture.jpg file using the file API to o ...

Exploring AngularJS: Custom directive for accessing the min attribute value of an input[date] element

I am attempting to gain write access to the <input type="date" min attribute from within my custom directive value. I am aware that the input[date] element is a directive as well. You can read more about it at this link. Using $(elem).attr('min&apo ...

Steps to disable fancybox for a specific selector

I am facing an issue with unbinding fancybox associated with anchor links having a specific class. Here is an example: <a class="group">some code here</a> To bind fancybox to elements with the class 'group', I use the following code ...

Ajax request triggers a page refresh

As I review the AJAX call within a React method, there are some key observations: handleActivitySubmit: function handleActivitySubmit(activity, urlActivity, callbackMy) { console.log("querying with activity: " + JSON.stringify(activity)); $.ajax ...

Enhancing MongoDB query efficiency using Promise technology

At the moment, I am deeply involved in a personal project that is presenting a challenge with two different approaches to querying MongoDB. CustomerSchema.methods.GetOrders = function(){ return Promise.all( this.orders.map(orderId => Order. ...

Implementing Google Ads Code in NextJS for Automated Units

I'm currently working on a NextJS project and I need to integrate the Google AdSense code for automatic ads. The Google ad code I have is: <script async src={`https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=${process.env. ...