Whenever the user hits the "Enter" key, a new element will be generated and added to the bottom of an existing element

I am in need of creating a new element at the end of another element. For instance, let's say I have this element:

<div id="elmtobetrig">Element that should be followed by another element when the user hits enter after this text. <!--Element placeholder--></div>
I have tried the following code:

<div contenteditable="true" id="elmtobetrig"></div>
    <script>document.addEventListener("keyup", function(event) {
    if (event.keyCode === 13) {
      document.querySelector("div#elmtobetrig").createElement("line").innerHTML = "<br> This content should appear at the bottom of the element &nbsp; "
    }
  });</script>

However, it seems that using createElement() on a specific element is not possible... Is there an alternative way to achieve what I am attempting?

Answer №1

It seems like there is an issue with how you are creating the line element.

  • First, you should utilize the document.createElement method
  • Next, use .innerHTML to insert text into the element.
  • Finally, make sure to use .append to add the element to a parent element.

<div contenteditable="true" id="elmtobetrig"></div>
<script>
  document.addEventListener("keyup", function(event) {
    if (event.keyCode === 13) {
      let line = document.createElement("line")
      line.innerHTML = "<br> this should go to the bottom of the element &nbsp; "
      document.querySelector("div#elmtobetrig").append(line)
    }
  });
</script>


Explanation

The createElement() method creates the specified HTML element using the provided tagName, but it does not automatically append the element to any parent.

Remember to create the element, set its attributes, and then ensure that you append it to a parent element. If you skip the appending step, the element will not be added to the DOM correctly.

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

What is the best way to initiate a TouchEvent in a qunit test being run by grunt using only vanilla JavaScript?

I have implemented callbacks for different touch events that require testing. For example, the 'touchstart' event utilizes touch coordinates to configure a class member: NavigationUI.prototype.touchStart = function(evt) { this.interacting = ...

Is there a way to immobilize an object in JavaScript without resorting to Object.freeze()?

Is there a way to freeze the following object without relying on Object.freeze()? Let's find out: const obj = { a:'test', b:'Something' } ...

Do we need to use the render method in ReactJs?

I'm curious about how ReactJs uses its Render() functionality. Let's say we have some HTML code within index.html: <section id="Hello"> <h1>Hello world</h1> <p>Something something Darkside</p> </section&g ...

Can a JavaScript function spontaneously run without being called upon?

<a onclick="determineCountry(data)" class="installbtn">Install</a> My goal is to have the user redirected to one of three sites based on their location when they click the button above. However, there seems to be an issue with the script below ...

It is not possible to alter or manipulate dynamic content received from an Ajax/JSON response when creating a dynamic PHP form

I am in need of a dynamic form that functions as follows: Upon clicking the "ADD" button, a new <div> element should appear for selecting a package. Based on the selected package, the row should change its color by adding or removing certain classe ...

Success message displayed for Ajax form submission, yet email delivery remains pending

In my PHP code for sending emails, I have a function called "Send to friend" that works perfectly with standard PHP post. This confirms that the sendtomail.php file is functioning correctly as well. /* AJAX Code for Send to Friend */ $(function() { $(&ap ...

Tips on utilizing browser scroll for horizontal overflow of internal div?

I'm working on creating a dynamic page with a tree-like structure that easily exceeds the width of the browser window. My goal is to enable horizontal scrolling for the entire page using the browser's scrollbar, without needing a separate scrollb ...

Utilize JQuery scripting to input Checkbox values

Using this JQUERY code to populate data into an HTML table. The first time it displays checkbox values, but the next time it does not show the values that were shown the first time. See the JQUERY code below: $(document).ready(function(){ $('#det ...

Utilizing previously written HTML code snippets

While working on a page within a legacy application, I find myself repeatedly reusing a large HTML block of code. The entire HTML and JavaScript codebase is quite old. The specific HTML block in question spans over 200 lines of code. My current strategy in ...

The placement is set to absolute, with a designated height

Here is an example http://jsfiddle.net/HnfCU/ I am using jQuery to toggle the visibility of the .child div. The position of the .child is set to absolute relative to its parent element, .parent. The challenge I am facing is adjusting the height of the .ch ...

Is React.js susceptible to XSS attacks through href attributes?

When user-generated links in an href tag appear as: javascript:(() => {alert('MALICIOUS CODE running on your browser')})(); This code was injected via an input field on a page that neglects to verify if URLs begin with http / https. Subseque ...

phpif (the current date is after a certain specific date, do

Can someone please help me solve this problem? I want to prevent echoing a variable if the date has already expired. Currently, my PHP code displays: Match 1 - April 1, 2015 Match 2 - April 8, 2015 What I need is for Match 1 to not be echoed if the cur ...

Creating a radial gradient texture using CSS

I'm encountering an issue with my radial gradient and texture combination. Here is the code snippet I am using: background-image: url('../img/texture.png'); /* fallback */ background: -moz-radial-gradient(rgba(253,253,253,0.1) 0%, rgba(2 ...

The original items are not utilized by jquery-ui autocomplete

I currently have the following setup: class Team { constructor(data) { this.id = data && data.id || null this._title = data && data.title || null } get title() { return this._title } set title(v) { this ...

Tips for declaring the project npm registry within the package.json configuration file

Currently, I am juggling multiple projects simultaneously and facing the issue of each project having a different node module registry. For instance, project A sources its modules from http://registroy.foo.com, while project B pulls modules from http://re ...

Utilize the fetch function to showcase information retrieved from a specific endpoint on a webpage using Javascript

Hey there, I have a Node server with an http://localhost:3000/community endpoint. When I make a GET request to this endpoint, it returns information about three different users in the form of JSON objects. [ { "avatar": "http://localhost:3000/avatars ...

Encountering an "Unmet Peer Dependency" error message while attempting to integrate bootstrap-ui into my Angular project

Currently, my goal is to successfully install angular-ui. Following the tutorials, I have attempted all commands such as: npm install angular-bootstrap However, this command results in an error message: +-- UNMET PEER DEPENDENCY angular@>=1.5 After ...

When you hover over a Wordpress page, the entire text on the page will be underlined

Currently designing my own website using WordPress with the Elementor free plugin and Phlox theme. I've made some progress by completing a few sections which include text, buttons, and images. However, I'm encountering an issue where all the text ...

Is it possible that the passing of Form Serialize and list to the controller is not functioning properly?

i am struggling with the following code in my controller: public ActionResult SaveWorkOrder(DTO_WorkOrder objWork, List<DTO_PartsWO> listTry) { //something } here is my model : public class DTO_WorkOrder { public string Id { get; set; ...

Tracking Time Spent in a Tab using HTML and JavaScript

I have a unique issue that requires a specific solution. Despite my extensive search across the internet, no useful answers were found. This is the snippet of HTML code in question: <form action="/timer.php" method="POST"> <span>Fir ...