What is the best way to delete multiple highlighted contenteditable elements in HTML?

Is there a way to easily delete multiple HTML elements by selecting them and pressing the Backspace key? This functionality is available in the WordPress block editor as well as Editor.js. Users can highlight several blocks and remove them with a simple keystroke. To achieve this, one would need to select (not click) the .block-1, .block-2, .block-3 sections and then press the Backspace key to delete them.

[IMPORTANT]

  1. Make sure each block has the contenteditable attribute.
  2. For a demonstration of what I am looking for, please visit Editor.js.
<div class="block-1" contenteditable="true"> 1st Block </div>
<div class="block-2" contenteditable="true"> 2nd Block </div>
<div class="block-3" contenteditable="true"> 3rd Block </div>
<div class="block-4" contenteditable="true"> 4th Block </div>

https://i.sstatic.net/G2At4.png

Answer №1

We require 2 listeners:

  • 1 - on mouseup, which captures the selected text, uses TreeWalker to retrieve all highlighted elements and toggles the selected class on .blocks.
  • 2 - on keyup, designed to detect backspace actions

Edit:

Utilized This link to enhance the answer .

$(document).on({
  'keyup': function(e) {
    if (e.which == 8)
      $('div.block.selected').remove();
  },
  'mouseup': getSelectedElementTags
});


function rangeIntersectsNode(range, node) {
  var nodeRange;
  if (range.intersectsNode) {
    return range.intersectsNode(node);
  } else {
    nodeRange = node.ownerDocument.createRange();
    try {
      nodeRange.selectNode(node);
    } catch (e) {
      nodeRange.selectNodeContents(node);
    }

    return range.compareBoundaryPoints(Range.END_TO_START, nodeRange) == -1 &&
      range.compareBoundaryPoints(Range.START_TO_END, nodeRange) == 1;
  }
}

function getSelectedElementTags() {
  var win = window;
  var range, sel, elmlist, treeWalker, containerElement;
  sel = win.getSelection();
  if (sel.toString().length == 0) return
  if (sel.rangeCount > 0) {
    range = sel.getRangeAt(0);
  }

  if (range) {
    containerElement = range.commonAncestorContainer;
    if (containerElement.nodeType != 1) {
      containerElement = containerElement.parentNode;
    }

    treeWalker = win.document.createTreeWalker(
      containerElement,
      NodeFilter.SHOW_ELEMENT,
      function(node) {
        return rangeIntersectsNode(range, node) ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_REJECT;
      },
      false
    );

    elmlist = [treeWalker.currentNode];
    while (treeWalker.nextNode()) {
      elmlist.push(treeWalker.currentNode);
    }
    elmlist.forEach(function(e) {
      if ($(e).hasClass('block')) {
        $(e).toggleClass('selected');
      }
    });
    sel.empty()
  }
}
div.block.selected {
  background-color: #ddf;
}

div.block {
  margin: 24px;
  border-bottom: 1px solid #ddd;
  font-size: 13px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container" contenteditable="true">
  <div class="block block-1" contenteditable="true"> 1st Block</div>
  <div class="block block-2" contenteditable="true"> 2nd Block </div>
  <div class="block block-3" contenteditable="true"> 3rd Block</div>
  <div class="block block-4"> 4th Block </div>
</div>

Answer №2

Here is a code snippet that eliminates the need for CSS and the contenteditable attribute:

var targeted;

document.getElementById('container').addEventListener('click', function(event) {
    console.log(event.target); // Identify the targeted element
    if(event.target.id !== 'container') {
        targeted = event.target;
    } else {
        targeted = undefined;
    };
});

document.addEventListener('keydown', function(event) {
    if(event.keyCode === 8 && targeted) {
        targeted.parentNode.removeChild(targeted);
    };
});
#container {
    padding: 20px;
    background-color: black;
}
#container div {
    margin-bottom: 5px;
    height: 50px;
    width: 200px;
    background-color: white;
}
<div id="container">
    <div contenteditable="true">1</div>
    <div contenteditable="true">2</div>
    <div contenteditable="true">3</div>
    <div contenteditable="true">4</div>
    <div contenteditable="true">5</div>
</div>

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 for utilizing nested loops along with promise map

I have the following code snippet: Promise.all(venue.map(venue => { return Promise.all(concat_all.map(tgl => { pool.query("INSERT INTO peminjaman_venue VALUES (?,?,?,?,?,?,?,?,?,?,?)", [id_event, venue, nama_lengkap_peminjam, ...

Is it possible to write CSS 3 rows without using the :not() selector for improved efficiency?

Consider using CSS code like the following in some cases: input:not([type="submit"]):not([type="checkbox"]):not([type="radio"]):not([type="file"]) { border:1px solid #fff; background-color:#f3f4f5; } <div><input type="text" name="alpha" /&g ...

How to automatically center Google Maps and update marker on responsive resize

Trying to figure out how to maintain the center of Google Maps while resizing responsively has been a challenge. I've successfully centered the map, but I'm struggling to include my marker in the JavaScript code so that it stays centered as well ...

What could be causing my webpage to freeze every time a filter button is selected?

Tasked with developing a webpage similar to Pinterest by utilizing data from a JSON response. Each JSON object contains a service_name key, which can be manual, twitter, or instagram. I made an effort to implement three filter buttons to only display the r ...

What could be causing my ul list to not be populated by ajax?

To populate the ul list with data from PHP code on page load, you can use the following ajax function. I appreciate any help in advance, and please forgive me if my explanation is not precise as I'm new here. This post contains mostly code snippets. ...

Ways to manipulate the placement of angular material 2 sidenav content to the bottom

I have been experimenting with various methods in CSS to override the existing side nav component in Angular Material 2. mat-sidenav-container { background: white; bottom: 0px !important; /* <---- no success */ } mat-sidenav { width: 300px; ...

Why does routing function correctly in a browser with AngularUI Router and Ionic, but not in Ionic View?

My Ionic App runs smoothly in the browser when using ionic serve. However, I encounter issues with routing when running the app in Ionic View (view.ionic.io) after uploading it with ionic upload. The index.html loads but nothing within <div ui-view=""& ...

The innovative technique of using pure CSS to secure the bottom edge of a div to the viewport

Is there a way to keep two container divs positioned x pixels from the bottom of the viewport without using position absolute|fixed? I want them to remain as position: relative for proper DOM flow. Searching for a CSS-only solution that works in IE7+. Mos ...

Callback function for asynchronous operations on the client side with Meteor

Is there a way to retrieve the value returned by an asynchronous callback in the client-side of Meteor before the stack continues executing? Here is code snippet as an example: var result=function(str){ Meteor.call("getSearch",str,function(err,res){ ...

Concerns arise with the swal destroy functionality

I have a working code for the Swal function, but when I click cancel without entering any information, it still triggers the AJAX call, which is not desired. $(document).on('click','.addon',function() { Swal.fire({ title: &apo ...

Encountering difficulties retrieving JSON response from Express in a production environment

When in Development mode, react and express connect flawlessly, allowing for successful data retrieval from the backend. However, in Production mode, although a status code of 200 is returned, the JSON response from express cannot be obtained. The specifi ...

An easy method to alter the color of the unique "special" character

Is there a way to customize the color of special characters like this one? <div style="color:red;">This text is red but the following symbol remains unchanged: &#10006 </div> It seems that the symbol is in fact an image, which explains wh ...

Utilizing web forms for dynamic CSS modifications

I'm working on developing a CMS using PHP and AJAX. My goal is to implement a form that can change the CSS styling for the entire website. Do I need to utilize a database or can I store PHP variables to achieve this functionality? Here's an exa ...

Silly problem arising from the animate feature in jQuery

Apologies for my poor English. I am facing an issue with the animate function of jQuery in my code snippet. It seems to work fine at line 2, but it doesn't work at line 3. Can someone help me understand why? $('.opac').hover(function(){ ...

What is the best way to place a child on top of a different parent in the stack?

There is a collection of figure tags, each with an expandable figcaption. Inside each figure, there is a clickable div that reveals the figcaption when clicked. However, the visible figcaption only overlaps the figure it belongs to and not others. Is there ...

Accessing a hyperlink within the existing page

How can I make a hyperlink in an HTML document that opens the linked document (link1.html) under the link on the same page? links.html: <body> <h3>Links</h3< <a href="link1.html">link1</a> </body> Desired out ...

Encountering a ReactJs and TypeScript error: "menuItems.map is not a function, issue with map method"

Greetings! I am currently working on implementing the logic of using useState and mapping an array to show only one dropdown item at a time. Below is my array structure with tags (menu name, links (to router), icon (menu icon), and if there are dropdown i ...

Avoiding Navbar Link Clicks due to Z-Index

Is it possible for the z-index or positioning of an element to hinder a user from clicking on a navbar link? When I visit my website , I find that I am unable to click on any of the links in the navigation bar. Could this be due to the z-index or position ...

How can I trigger the offcanvas opening in Bootstrap 5 through code?

I am having an issue with a bottom offcanvas on my webpage. I want to open it when a card is clicked, but despite trying to set the necessary attributes and using code from the documentation, it only shows the backdrop briefly before immediately dismissing ...

Using jQuery and Ajax to efficiently handle the retrieval of large files while browsing

I have some large text files that are potentially multiple GB in size, and I am looking for a way to view them within a div element. The idea is to make an AJAX request for a more manageable chunk of the file, have the AJAX script (preferably in PHP) inte ...