Transform the innerHTML of a contenteditable text element into a regular string format

When using a content-editable element, such as:

<span id="myinput" contenteditable="true">This is editable.</span>

and then trying to read its content from JavaScript with

document.getElementById('myinput').innerHTML
, you may encounter unexpected results, such as:

  • "blah " =>

    innerHTML = "blah &nbsp "

  • "bonjour\n bonsoir" =>

    innerHTML = "bonjour<br>bonsoir"
    (Firefox) and
    innerHTML = "bonjour<div>bonsoir</div>"
    (Chrome)

  • It seems that there are many other translations happening into HTML...

Is there a way to convert the innerHTML into normal text?

(e.g. for the examples: "blah " and "bonjour\n bonsoir")

Answer №1

Consider these methods:

// For Internet Explorer
document.getElementById('inputField').innerText

// For all other browsers
document.getElementById('inputField').textContent

If you need to handle line breaks, follow this approach:

var element = document.getElementById('inputField');
var nodes = element.childNodes;
var textContent = '';

for (var index = 0; index < nodes.length; index++) {                        
    switch(nodes[index].nodeName) {
        case '#text': 
            textContent += nodes[index].nodeValue;
            break;
        case 'BR':
            textContent += '\n';
            break;
    }
}
console.log(textContent);

Answer №2

Since the behavior varies across different browsers, it is necessary for you to handle this on your own:

var convert = (function() {
    var convertElement = function(element) {
        switch(element.tagName) {
            case "BR": 
                return "\n";
            case "P": // fall through to DIV
            case "DIV": 
                return (element.previousSibling ? "\n" : "") 
                    + [].map.call(element.childNodes, convertElement).join("");
            default: 
                return element.textContent;
        }
    };

    return function(element) {
        return [].map.call(element.childNodes, convertElement).join("");
    };
})();

To see it in action: http://jsfiddle.net/koyd8h59/1/

If you wish to include <h1> and other block-level tags, you will need to implement additional code.

Answer №3

Check out my response - it may not be flawless as some line breaks might disappear, but given the scarce information available, perhaps it will benefit someone.

const analyzeNode = node => {
    let data = ""

    for (const child of node.childNodes) {
      if (child.tagName === "BR") {
        data += "\n"
      }

      if (child.tagName === "DIV" && !child.querySelector("br")) {
        data += "\n"
      }

      if (child instanceof Text) {
        data += child.textContent
      } else {
        data += analyzeNode(child)
      }
    }

    return data
}

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

I continue to encounter a problem where GitHub refuses to navigate links, despite them being properly configured

While working on GitHub, I encountered an issue when trying to set up a website on GitHub domains - the links were not functioning properly. Here is an example of what I was dealing with: <!DOCTYPE html> <form action="homepage.html" meth ...

How can I expand and collapse elements using Angular?

I'm looking to implement a collapsible feature. When the user clicks on the "Section Title", I want the corresponding information to collapse or expand. @Component({ selector: 'knowledge-base', template: ` <div *ngFor="let sect ...

Position the Crossmark to align with text using CSS styling

How can I properly align a crossmark and a checkmark with the text behind them? The checkmark looks aligned well, but the crossmark appears to be slightly off to the top-right. I'm hesitant to adjust margins and paddings as it may cause issues when th ...

How to Save Styles as a CSS File in Angular 4

I'm a beginner in Angular 4 and I'm trying to export my styles as a css file. Whenever I serve or build the project, it generates a style.bundle.js file and includes the css as an html style element. However, I would like to export it as a style ...

Is your Vue.js chart malfunctioning?

I have been experimenting with chart.js and vue.js. The component I created is called MessageGraph, and it is structured like this (with data extracted from the documentation): <template> <canvas id="myChart" width="400" height="400">< ...

Encountering a Module node browserify issue

I recently attempted to utilize the Dyson module node from https://github.com/webpro/dyson#installation. However, upon executing the 'dyson' command, I encountered the following error in my terminal. $ dyson Prueba/ module.js:491 throw err ...

Choosing jQuery over JQuery Mobile for a standard web application to effectively manage different devices

Creating a Unique Web Application In the works is a unique web application, similar to Trello, that divides a page into columns where tasks/cards can be added and moved between them. This desktop-focused platform will feature an information column on the ...

What is the best way to include a distinct Navbar within the admin dashboard using react js?

I currently have an application that is functioning well with both an admin section and a user section. The new requirement is to separate the admin navbar from the user navbar. At the moment, the navbar is displayed in all routes, but I need it to be hid ...

What is the best way to send an HTML report through email with embedded images as an attachment?

Currently, I am in the process of generating a report using ExtentReports that will be distributed via email to team members who are outside of our domain. To capture screenshots of any test failures, I utilize a screenshot method which saves these images ...

PHP MySQL failing to add data to database

I am encountering an issue that I can't seem to solve. While I have checked the database and table names for correctness, inserted a table in phpmyadmin successfully, and tested the connection, I still can't get it to work on my site. Any help in ...

Most effective method for integrating a JS module across all browsers

I have created a robust library that I want to integrate into a different web project. This library handles all its dependencies and consists of js, css, and html files. My ideal scenario would be to package it as an npm module and simply use import to in ...

The picture won't stay within the confines of the container

As I work on my fitness site, I wanted to incorporate a sponsor section. While exploring some code that matched the style of my website, I discovered this snippet below. However, being new to CSS, I struggled with fixing it to ensure that the images fit ...

Issues with Materialize autocomplete drop-down functionality

I've been working on implementing materialize autocomplete in my project and have been facing issues with the dropdown not appearing. I tried using materialize version 0.98.2 from CDN as suggested, but it still doesn't seem to work. I suspect the ...

Colliding with sin() and cos() animations: Meshes entwined in motion

Greetings fellow developers! I'm excited to delve into JavaScript and Three.js with all of you. Below is the code snippet for creating 4 cubes and an arrow, resembling the image found here: Image1 // Scene const scene = new THREE.Scene(); // Groups ...

There seems to be an issue with the HighCharts chart export feature as it is not showing the Navigator graph

We are currently using HighCharts version 4.2.2 http://api.highcharts.com/highcharts/exporting While going through their exporting documentation, I made a decision to not utilize their default menu dropdown. Instead, I only needed access to the .exportCh ...

Retrieving the value of a button tag in JavaScript for an AJAX request

Essentially, I have a collection of <a> tags retrieved from a database. These tags are visible to users and trigger an ajax function when clicked on. Currently, one button serves the purpose for all tags. The structure of these tags is as follows: ...

Two conflicting jQuery plugins are causing issues

In my journey to learn jQuery, I encountered an issue while working on a website that utilizes a scroll function for navigating between pages. The scripts used in this functionality are as follows: <script type="text/javascript" src="js/jquery-1.3.1.mi ...

Display a PHP warning message when attempting to add methods to ajax jQuery

Recently, I have delved into the world of ajax and jQuery while working on my final year project. However, I have encountered a problem when adding methods to my JavaScript code. Here is an excerpt from my ajax script: $(document).ready(function() { $ ...

How can you modify a button in Ionic 2 based on the login status, using a modal to redirect to a different page once authenticated?

I have a button on my main page that is supposed to display 'Log out' when the user is currently logged in, and 'Log in' when there is no active user session. Clicking on the login button opens a modal. After successful login, the user ...

Issue with FiFO on MacOs causes skewed borders to not display correctly

I am currently facing an issue with my webpage and would greatly appreciate some help from the community. My goal is to create a skewed border inside a div, similar to the example on this JSFiddle link: https://jsfiddle.net/kx6f9rsd/ .container { backgro ...