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

Angular8: Adjusting Activity Status After Leaving Page

When performing activities like upload, download, delete, and edit, I display statuses such as 'upload started' or 'upload completed'. This works perfectly when staying on the same page. However, there are instances where a user may nav ...

Integrating a parameter into a plugin allows for displaying a specified number of elements in the output

A unique plugin is being used to create a vertical slideshow effect. This plugin scrolls the top-most div in a series of divs with the same class upwards, removes it from the container, and appends it to the bottom of the series within the container. The e ...

I'm looking for a solution to enable the execution of 'expandRowByClick' only when clicking on a specific area within the row in Ant Design. Any suggestions?

In my quest to create a expandable table row with Ant Design's built-in expandRowByClick function, I encountered a dilemma. The function allows me to expand a row by clicking anywhere in it, but what if I want this feature to apply only to a specific ...

Displaying and hiding the Angular <object> element

I am faced with a challenge involving managing files of various formats and creating a gallery with preview functionality. Everything works smoothly when clicking through items of the same format, like JPEGs. However, an issue arises when switching from vi ...

The loop within a loop is causing excessive lag and is on the verge of crashing the

I need help with optimizing the performance of my app that retrieves json data. The json file contains nearly one thousand words structured like this: {"THEMES":{"THEME1":["ITEM1","ITEM2","ITEM3"],"THEME2":["ITEM1",...]...}} The size of the file is aroun ...

Struggling with adding headers in React application

When I try to include an h1 heading, either the heading doesn't show up if I comment out the buttons, or if I comment out the heading, then the buttons don't display. But when both are included, nothing is displayed. Any suggestions on how to fix ...

Is jQuery the solution for tidying up messy HTML code?

Is there a way to clean up this markup using jQuery? <span style="font-size:19px"> <span style="font-size:20px"> <span style="font-size:21px"> Something </span> </span> </span> I'm looking to tra ...

Experiment with altering the layout of certain navigation bars

I am currently attempting to customize the background color and text color for specific HTML components. Within my project, there are 3 navigation bars. I aim to establish a default color for all nav bars while also altering the specific color of one of t ...

Using jQuery Datatables fnReloadAjax successfully triggers a reload of the data, however, it

In my jQuery datatable, I am utilizing the code below to refresh the data: $(".unread-rows").click( function(e) { e.preventDefault(); message_table.fnReloadAjax("/letters/ajax/inbox/1"); message_table.fnDraw(); $(this).addClass("active").s ...

Creating a jQuery alertbox that is triggered by specific elements in an anchor tag

I am working on an HTML page that contains 50 A tags. I am trying to figure out how to create an alert based on a specific element inside the A tag. Here is an example of what I am looking for: <a href "something">click to see the alert</a> ...

Warning: Close button position is unmanageable

This is what the alert and close button should look like on my website, based on Bootstrap's design. However, after implementing it into my site, it ended up looking like this. I attempted to modify the bootstrap.min.css file, but the changes did not ...

Align the reposition button with the pagination in the datatables

I am looking to adjust the placement of my buttons. The buttons in question are for comparison, saving layout, and printing. I would like them to be inline with the pagination, as I am using datatables here. <table id="sparepart_id" cellspacing="0" ...

Having trouble storing radio buttons and checkboxes in MySQL database using AJAX

My app is facing an issue where radio buttons and checkboxes are not correctly entering information into the database. Currently, only text fields are successfully saving data, while checkboxes and radio buttons are only recording the value of the first ra ...

modify CSS style once the modal has been hidden

Is there a way to change the default background color of my table row back to normal after closing the modal window that appears when I click on it? <tr class='revisions'> <td>{{ $revision->date_of_revision->format(' ...

Live AJAX inquiries in progress

Is there a way to track the number of active AJAX requests in jQuery, Mootools, or another library similar to Prototype's Ajax.activeRequestCount? I am looking for a method that can be used across different libraries or directly through XMLHttpRequest ...

A guide to selecting the dropdown item labeled as (Select All) using Python and Selenium

edit: Trying to submit parameters for a database-generated report on this page. Successfully modified the start date in the first field using send_keys(), but unable to click on "(Select All)" for fields 3 and onwards, except one. In order to access the h ...

Firebase Error: Trying to access properties of null object (indexOf)

Whenever I try to console.log(docSnap), a Firebase error shows up as seen in the image below. Despite attempting various solutions, none have proved effective. useEffect(() => { if (folderId === null) { dispatch({ ...

Comparing the architecture of two JSON objects in JavaScript without taking into account their actual content

One of the tools I rely on for my projects is a Node.js based mock server that helps me specify and mock API responses from the backend. However, it would be beneficial to have a way to ensure both the backend and frontend are in sync with the specified st ...

Create a personalized Command Line Interface for the installation of npm dependencies

I am looking to develop a Node CLI tool that can generate new projects utilizing Node, Typescript, Jest, Express, and TSLint. The goal is for this CLI to create a project folder, install dependencies, and execute the necessary commands such as npm i, tsc - ...

Issue with the Navigation in CSS and jQuery

I'm struggling to understand a problem with the desktop navigation on this website, specifically in Safari on certain pages. The issue seems to only occur on Safari for Windows, Mac Desktop, and Mac Laptop. Interestingly, the navigation works perfect ...