Incorporating user input into a div element

So, I'm in the process of building my own Task Tracker using JavaScript to enhance my skills, but I've hit a roadblock.

I successfully implemented adding a new div with user-inputted tasks, however, there's no styling involved.

<div class="isDo"> // HTML code
  <p id="newTask">Task 1</p>
  <hr>
</div>

function addTask() { // JavaScript Code
  var div = document.createElement("div");
  var taskAdd = document.getElementById("taskAdd").value;

  div.innerHTML = taskAdd;

  document.getElementsByClassName("isDo")[0].appendChild(div);
}

While when I append a paragraph instead of a div, it works fine with styling. However, I want to include an <hr> tag after each input value.

Is there a way for me to dynamically add an entire div consisting of a paragraph and an <hr> tag in this scenario?

Answer №1

This solution should work perfectly for you :) `

  <!DOCTYPE html>
  <html lang="en">
    <head>
      <meta charset="UTF-8>;
      <title></title>
    </head>
      <body>
        <div class="isDo"> 
          <p id="newTask">Task 1</p> 
          <hr>
      </div>
      <button id="btn" >Add Tag</button>

       <script>
         function addTask() { // JavaScript Function
           var div = document.createElement("div");
           var taskAdd = document.getElementById("newTask").innerHTML; 
           div.innerHTML = `<p>${taskAdd}</p><hr>`; 
           document.getElementsByClassName("isDo")[0].appendChild(div);
         } 
         var btn = document.getElementById("btn")
                           .addEventListener("click", addTask);
      </script>
    </body>
  </html>

`

Answer №2

Feel free to give this a try:

<!DOCTYPE html>
<html>
<title>Test Code</title>
<head>
<script>
function addNewTask() {
  var div = document.createElement("div");
  var newTask = document.getElementById("newTask").value;
  div.innerHTML = newTask + "<hr>";
  document.getElementsByClassName("tasks")[0].appendChild(div);

}
</script>
</head>
<body>
    <input id="newTask">
    <button onclick="addNewTask()">Add Task</button>
    <div class="tasks">
        <p id="task1">Task 1</p>
        <hr>
    </div>
</body>
</html>

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

Increase the size of a centered image within a table

Lately, I've felt like my mind is starting to unravel. Here's the issue at hand: I've been attempting to resize an image within a table cell so that it spans the full width of the cell. Strangely enough, this seems to be harder than anticip ...

New to AppleScript: Encountered an unexpected identifier instead of the expected end of line

tell application "Microsoft Word" activate insert text "property eGrepx : "priceValue___11gHJ\">\\$\\d{2},\\d{3}.\\d{2}" " at end of text object of active document e ...

What is the best way to create a function that will return a Promise within an Express Route?

I am working with a business level database module named "db_location" that utilizes the node-fetch module to retrieve data from a remote server through REST API. **db_location.js** DB LOGIC const p_conf = require('../parse_config'); const db_ ...

Attempting to use express and nodemailer to send an email, but there is absolutely no output appearing in either the console or the terminal

When I click the send email button, it should send the data to a mailhog inbox. However, nothing happens - no errors in the console or terminal. My goal is to use nodemailer to send the name, email, chosen plan, and message from the form to the mailhog add ...

Utilizing ReactJS and TypeScript to retrieve a random value from an array

I have created a project similar to a "ToDo" list, but instead of tasks, it's a list of names. I can input a name and add it to the array, as well as delete each item. Now, I want to implement a button that randomly selects one of the names in the ar ...

Problem with exporting default class in Babel/Jest conflict

Currently, I am facing a challenge while testing the code using jest. The issue seems to be related to babel, especially regarding the export of a default class. Here is an example of the code causing the problem... export default class Test { get() { ...

Accessing elements within a ReactJS map structure using the material-ui Selectable List component is not supported

I'm facing a dilemma. Unfortunately, my proficiency in English writing is not up to par... ※Please bear with me as it might be hard to follow. I'm trying to choose the ListItem component, but for some reason, I can't select the ListIt ...

What is the process of specifying that an Angular directive must act as a child directive within a particular directive in Angular?

I am currently developing a directive for AngularJS. How can I specifically configure it to require being a child of directiveA? For instance, consider the following example: <my-modal> <m-header>Header</m-header> </my-modal> ...

Error in Node.js: Attempting to modify headers after they have already been sent to the client

I've been facing the challenge mentioned in the topic for quite some time now. Is there anyone who can assist me with this? Feel free to ask any questions if you need clarification. I've gone through a few potential solutions for this issue, but ...

Character count in textarea does not work properly when the page is first loaded

As English is not my first language, I apologize in advance for any grammar mistakes. I have implemented a JavaScript function to count the characters in a textarea. The code works perfectly - it displays the character limit reducing as you type. However, ...

Mean stack authentication issue: missing token

Overview: Currently, I'm in the process of developing an application that utilizes node/express for the backend, mongo as the database, and angular for the frontend. User authentication is handled through jsonwebtoken, where a token is stored in local ...

The Data from Req.Body Doesn't Appear After Adding Form Fields

I've been struggling to find a solution to this issue, but here's the gist of it: I have a button that allows users to add a question and answer pair one at a time by clicking on an "Add Question" button. This is achieved through the append featu ...

Several queries for directions on Google Maps are resulting in the same response being returned for all requests

I've been experimenting with the Google Maps Directions service to retrieve three different travel methods for the same route (driving, walking, and bicycling). Despite successfully iterating through the array of methods and setting them in the respec ...

Is it possible in ReactJS to return JSX from a callback function?

After spending some time working with react, I encountered a basic issue that has me stumped. In the Login component, I am submitting a form and if it returns an error, I want to render a snackbar message. handleSubmit = (event) => { event.preven ...

The PhpStorm/JavaScript expression statement doesn't involve assignment or function call

I am striving to enhance the cleanliness of my method. Based on the value of an integer number, I am generating different date formats, resulting in the following: getRanges() { var currentDate = new Date(); //This can ...

Determine whether the color is a string ('white' === color? // true, 'bright white gold' === color? // false)

I am facing an issue with multiple color strings retrieved from the database. Each color string needs to be converted to lowercase and then passed as inline styles: const colorPickerItem = color => ( <View style={{backgroundColor: color.toLowerC ...

Executing the executeScript method in Microsoft Edge using Java and WebDriverWould you like a different version?

I'm currently attempting to execute the following code in Microsoft Edge using WebDriver ExpectedCondition<Boolean> jsLoad = driver -> ((JavascriptExecutor) driver).executeScript("return document.readyState").toString().equals(&quo ...

What could be hindering the activation of my button click event?

Below is the js file I am currently working with: var ButtonMaximizer = { setup: function () { $(this).click(function(){ console.log("The maximize button was clicked!"); }); } }; $(docum ...

How can you efficiently transfer the expression utilized in v-for from the template to the component code?

How can I extract the expression within the template that is contained in :class? <div v-for="(user, index) in users" :key="index" :class="{'bg-yellow-lighter': infoWindowMarker && infoWindowMarker.position.lat === user.posit ...

Using prevState in setState is not allowed by TypeScript

Currently, I am tackling the complexities of learning TypeScipt and have hit a roadblock where TS is preventing me from progressing further. To give some context, I have defined my interfaces as follows: export interface Test { id: number; date: Date; ...