JavaScript issue: event.target.innerText not preserving line breaks

Within a conteneditable div, I am displaying pre-populated grey text with the data-suggestion attribute.

Upon clicking the text:

  1. The text color changes to black
  2. The data-suggestion attribute is removed from the selected line

An input event on the contenteditable div triggers the onInput() function, populating the text in the final_doc_summary variable.

Issue:

  1. The final_doc_summary variable does not preserve new lines when the event is triggered.
  2. I specifically want to include text without the data-suggestion attribute in the final_doc_summary variable.

<div
    id="div_textarea2"
    class="textarea mb-3"
    contenteditable="true"
    v-html="doc_summary"
    @input="event=>onInput(event,index)"
></div>


data(){
     return {
           final_doc_summary:'',
           suggestion_list : ['Line 1','Line 2','Line 3'],
     }
}

    mounted(){
      this.AddSuggestedLine();    

}

methods: {
    onInput(event, index){
      this.final_doc_summary  = $(event.target).text();
      
    },

    AddSuggestion1() {
      for (var i=0;i<this.suggestion_list.length; i++){
        var suggestions  = "<div><span data-suggestion=true class='suggestedContent' id='suggested-content-"+i+"'>" +this.suggestion_list[i]+ "</span></div>";
        this.doc_summary +=suggestions;
      }
    },
}

The following jQuery code changes text to black and removes the data-suggestion attribute:

  $(".suggestedContent").click(function () {
    $(this).css({ color: "black", "text-decoration": "none" });
    $(this).removeAttr('data-suggestion');
  });

Answer №1

Consider using event.target.textContent instead of other methods.

https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent

It's important not to confuse Node.textContent with HTMLElement.innerText. Despite their similar names, there are significant distinctions:

textContent retrieves the content of all elements, including <script> and <style> elements, while innerText only displays "human-readable" elements.

textContent returns every element in the node, whereas innerText takes into account styling and does not return text from "hidden" elements.

Additionally, you may need to incorporate some JavaScript to add a newline (\n) when the user presses enter. By default, the browser adds a <br> on enter. Ensure to set the CSS style white-space: pre-line for proper rendering of newlines.

<div
id="div_textarea2"
style="white-space: pre-line"
class="textarea mb-3"
contenteditable="true"
v-html="doc_summary"
@keydown.enter.prevent="addNewLine"
@input="event=>onInput(event,index)"
methods: {
  addNewLine (event) {
    const selection = window.getSelection()
    const range = selection.getRangeAt(0)

    // create a new text node with a newline character
    const newline = document.createTextNode('\n')

    // insert the newline at the current caret position
    range.insertNode(newline)

    // move the caret to the end of the newline
    range.setStartAfter(newline)
    range.setEndAfter(newline)
    selection.removeAllRanges()
    selection.addRange(range)
  }
}

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

Issues with setting headers after they have been sent - Can you explain why?

How am I setting a header after it has been sent to the client? Here is the code snippet: When a form is submitted, a post ajax request is triggered which returns a JSON object to the client. I have commented out most of the code to troubleshoot, and cur ...

Retrieving data from the <script> tag and transferring it to the t-esc tag within Odoo 12

After attempting to retrieve the current coordinates of a location in Odoo, I successfully obtained longitude and latitude data through an alert generated by the following code: <button onclick="getLocation()">Try It</button> ...

The 'Cross domain jQuery Ajax request using JSONP' triggered an error: SyntaxError - Unexpected token : appeared on the screen

I've been struggling to extract information from the steam api, encountering persistent difficulties due to the error mentioned above. Below is the snippet of code I have been utilizing: var steamurl = "https://api.steampowered.com/IDOTA2Match_570/Ge ...

Explore the HTML code of a webpage to locate a specific attribute, and then identify the parent div element associated with that attribute

Is there a way to identify the parent div ID in javascript or jquery by searching HTML src for a specific attribute or text? Consider the following code snippet: <div id="ad_creative_1" class="ad-div mastad" style="z-index: 1;"> <script>(func ...

Enhancing JavaScript Asynchronous Programming with EventLoop and async/await

Exploring the intricacies of how JavaScript processes asynchronous methods led me to dive into async/await. In an effort to gain a complete understanding, I crafted the following example: async function first() { console.log(9); await Promise.resolv ...

Failure to trigger AJAX Success or Error Events

I'm struggling to understand why this code isn't working or find any relevant resources. When I check the json object in Firebug, it either returns success: false or success: true from the post request, so I'm confused as to why the function ...

Modifying an image with jQuery

Why won't this image change? Below is the relevant HTML, CSS, and jQuery code. HTML <nav id="desktop-nav"> <div class="logo"> <a href="#"></a> </div> <div> ... </div> ... CSS nav#desktop-nav . ...

I'm feeling a bit lost with this API call. Trying to figure out how to calculate the time difference between the

Currently, I am working on a project for one of my courses that requires making multiple API calls consecutively. Although I have successfully made the first call and set up the second one, I find myself puzzled by the specifics of what the API is requesti ...

Splitting up JavaScript and HTML within a WordPress environment

I recently came across a discussion on separating PHP code and HTML at this link I find myself in a similar predicament. My current project involves designing a WordPress website with numerous sliders, animated dropdowns, forms, and other components. The ...

Utilizing Selenium WebDriver to extract links located within numerous Span tags

I am looking to count and list the number of links within different Span Tags. Within the provided HTML code snippet, there are two anchor links under 'Upcoming Event' Span, and 4 links under the 'Recent Free LIVE Webinars' section. Ca ...

Displaying real-time server responses using jQuery, PHP, and AJAX

Is there a way to display server response in real-time as it is being sent during a long and time-consuming request? Scenario: 1) A JQuery function sends an AJAX request to the server and opens a Dialog widget to wait for the response to update the conte ...

Implement a callback function for unchecked checkboxes on change

Currently, I am working with a gridview that includes a checkbox field. My goal is to use jQuery to create a function that activates when an unchecked checkbox is checked. function clickAllSize() { alert("helloy"); } $(document).ready(function () { ...

How come I am able to reference a component in styled-components while others cannot?

When using styled-components, you can reference another React component using the syntax ${Label}. However, I have noticed that it only works with certain components and not others. Despite reading the documentation at , I encountered an issue when trying ...

Best practices for timeout in HTTP long polling

As an avid user of Javascript AJAX and long-polling, I am constantly seeking the best value for server response timeout. Despite scouring numerous documents, a detailed explanation for timeout continues to elude me. Some suggest 20 seconds, while others ...

I am attempting to initiate a password reset process within vue.js

How can I fetch information using this link in vue.js http://localhost:2020/rest-password${token}&id=${data._id} Below is my code snippet: const submit = async () => { console.log('e'); try { const user = await axios.post( ...

The technique of using Javascript x to escape characters is

I've come across a handful of other software programs that feature a similar construct: let str = '\x32\x20\x60\x78\x6e\x7a\x9c\x89'; As I experimented with the sequence of numbers and letters within ...

Execute a Node script using PHP exec, retrieve the data in PHP, and then apply the finally method

I'm working on a PHP script that utilizes the exec function to run a Node script and then return some data back to the PHP script. The challenge I'm facing is finding a way to send the data back to PHP without having to wait for the cleanup code ...

After installing grunt, the Gruntfile cannot be located. How can this issue be resolved?

After installing grunt, I encountered a problem. Despite trying some commands suggested on stackoverflow in this How to install grunt and how to build script with it, running the grunt command still shows the same result. What steps should I take next?ht ...

The shopping cart in our e-commerce website is refreshed in real-time thanks to the integration of J

I am currently enhancing the Codeigniter Cart with JQuery by making an Ajax call for updates. Below is my JQuery function: $(function() { $('.cart_form select').on('change', function(ev) { var rowid = $(this).attr('c ...

Can you explain the functionality of the const handleChange = (prop) => (event) => {} function and its significance?

While going through the documentation for MUI, I stumbled upon a new syntax for arrow functions in JavaScript that I haven't seen before. I tried to figure out how it works but couldn't find any information on it. The syntax looks like this: con ...