The function getSelection().focusNode does not function properly within a specified ID

My current code allows for text to be bolded and unbolded using Window.getSelection(). I found the initial solution here: Bold/unbold selected text using Window.getSelection()

It works perfectly without any issues. However, when I tried to modify the code to only select text within a specific div with an id, I came across this solution: How to getSelection() within a specific div?

Upon combining both solutions, I noticed that the text was always bolded and never unbolded.

Here is my code snippet:

function addBold(){

      // validate selection inside specified div
      if(window.getSelection().baseNode.parentNode.id !== "editor") return;

      const selection = window.getSelection().getRangeAt(0);
      let selectedParent = selection.commonAncestorContainer.parentElement;
      let mainParent = selectedParent;
      
      if(selectedParent.closest("b")) {
        var text = document.createTextNode(selectedParent.textContent);
        mainParent = selectedParent.parentElement;
        mainParent.insertBefore(text, selectedParent);
        mainParent.removeChild(selectedParent);
        mainParent.normalize();
      } else {
        const span = document.createElement("b");
        span.appendChild(selection.extractContents());
        selection.insertNode(span);
        mainParent.normalize();
      }
  
      if (window.getSelection) {
        if (window.getSelection().empty) { 
          window.getSelection().empty();
        } else if (window.getSelection().removeAllRanges) { 
          window.getSelection().removeAllRanges();
        }
      } else if (document.selection) { 
        document.selection.empty();
      }

    };
    
<div id="editor" contenteditable="true">
      You are the programmers of the future 
    </div>
  
    <button onclick="addBold()">Bold</button>

Combining the two answers resulted in always bolding the text and ignoring the unbold functionality. Deleting the first line of the validation condition: if(window.getSelection().baseNode.parentNode.id resolved the issue and allowed for successful bolding and unbolding of text.

Answer №1

When creating bold text, the parent element of the text is identified and located. Text However, it fails to locate the main parent element correctly, so in order to make it work efficiently, the first line should be replaced with the following line: Replace

If window.getSelection().baseNode.parentNode.id is not equal to "editor"

Change it to:

If window.getSelection().focusNode.parentElement.closest("editor") does not have an id of "editor"

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

Tips on creating a literal type that is determined by a specific value within an object

In the flow, I am able to create a dynamic literal type in this manner: const myVar = 'foo' type X = { [typeof myVar]: string } const myX: X = { foo: 1 } // will throw, because number const myX: X = { foo: 'bar' } // will not throw ...

displaying a pair of distinct elements using React techniques

I need help adding a react sticky header to my stepper component. When I try to render both components together, I encounter an error. To troubleshoot, I decided to render them separately. Surprisingly, when rendering separately, I do not get the "store is ...

Node.js and Express: ensuring completion of asynchronous operation before responding to HTTP request

Imagine there is a callback function set up for an HTTP GET request, structured like this: router.get('/latestpost', function(req, res, next) { var data = new FbData(); get_latest_post (data); get_post_image (data); res.json(da ...

Filtering an array using criteria: A step-by-step guide

Currently, I am developing a system for Role Based permissions that involves working with arrays. Here is an example of the array structure I have: let Roles = { [ { model: 'user', property: 'find', permission: 'allow' ...

Expressjs Error- ReferenceError: cors has not been defined in this context

While working on creating a backend using ExpressJs, I encountered an error when running the backend. app.use(cors()) ^ ReferenceError: cors is not defined at Object.<anonymous> (C:\Users\hp\Desktop\Entri\kanba\ ...

Unexpectedly, the digit '1' has mysteriously appeared on my website without any explanation

I have noticed that the number "1" is appearing on my website without me having implemented it myself. Currently, I am using a template.php file to manage page creation. I simply import the content code into a $the_content variable and then print it. To ...

AJAX request lacks the 'access-control-allow-origin' header

I'm currently integrating a weather API into my app to display real-time weather information. Although I've used this API before, I am now attempting to fetch the data asynchronously using AJAX to avoid full page reloads. Below is the JavaScrip ...

Create a loop in Vue.js 3 without the need for a query

Can someone help me understand how to fetch data using a loop in Vue.js version 3 when working with queries? I am trying to retrieve an object based on its id, which is obtained from the URL. However, I seem to be facing some difficulties. Any guidance wou ...

I am attempting to incorporate a List View within a Scroll View, but they are simply not cooperating. My goal is to display a collection of items with additional text placed at the bottom

This is how it should appear: item item item item additional text here I am trying to create a layout where the list is in List View for benefits like virtual scrolling, but the entire layout needs to be within a Scroll View. I want to be able to con ...

Tips for extracting data from an Angular object using the *ngFor directive

https://i.stack.imgur.com/ai7g1.png The JSON structure displayed in the image above is what I am working with. My goal is to extract the value associated with the key name. This is the approach I have taken so far: <span *ngFor="let outlet of pr ...

What is the necessity of explicitly requesting certain core modules in Node.js?

The documentation explains that certain core modules are included in the Node.js platform itself and are specified within the source code. The terminology can get a bit confusing when it comes to details. The term "global objects" (or standard built-in obj ...

Displaying postcode on a category page: A step-by-step guide

I would like to showcase the user input code and present it on the web exactly as entered. <?php #code... ?> Any assistance is greatly appreciated. Please excuse my English. Thank you! ...

Utilizing Selenium for web scraping on Google Maps consumes an excessive amount of data

Scraping travel times from Google Maps is a task I have successfully accomplished. The code below scrapes travel times between 1 million random points in Tehran utilizing multiprocessing for efficiency. You can run the code provided in a terminal environme ...

The Vue ChartJS fails to display properly after the page is refreshed

Although this issue may appear to be a common one, some of the suggested solutions are outdated or no longer functional. My objective is to ensure that the chart remains responsive even after the page reloads. I attempted to implement the solution provided ...

How can we combine refs in React to work together?

Let's consider this scenario: I need a user to pass a ref to a component, but I also have to access that same ref internally. import React, { useRef, forwardRef } from 'react'; import useId from 'hooks/useId'; interface Props ext ...

Easy jQuery Mobile and AJAX login solution

My current project involves creating a mobile app with user login capabilities using PhoneGap, jQuery Mobile, AJAX, and PHP. I am starting with a basic HTML and PHP structure as I am not an experienced programmer, but even my simple user login form is not ...

Placement: fresh column in absolute position

Could someone please help me understand this situation? I have posted my code on jsfiddle. I am using Bootstrap 4. In my design, I have text placed over an image with the parent div having position:relative. The left div has position:absolute and left:2%, ...

What is the significance of having multiple route parameters in Express?

The RESTful API provided by cex.io offers a route that can return pairs of all currencies with a variable amount of parameters. In express, how can we achieve similar functionality? Consider the following pseudo code example... app.get('/pairs/:arg ...

Enhancing the current Node.js, Express, MongoDB, and Socket.io stack with the integration of AngularJS

After spending some time developing a web app using Node.js, Express, MongoDB, Mongoose and Socket.io, I've successfully released version one. Looking ahead to version two, my plan is to revamp the UI completely and switch to a front-end framework lik ...

What is the correct way to utilize Array.reduce with Typescript?

My current approach looks something like this: [].reduce<GenericType>( (acc, { value, status, time }) => { if (time) { return { ...acc, bestValue: valu ...