Developing an interactive input field using JavaScript's Document Object Model (DOM)

I am struggling with creating an editable text field using JavaScript. I have come across a function that allows for editing, but I am unsure if it is possible to change the title from High School to Middle School, which is generated by the function createTextNode.

My confusion lies in how to use the statement

addEvent(document.getElementById("h1"), "click", new Function("edit(this)"));
to add an event for editing the text field. You can run the code snippets to see the result.

Try the fiddle

var school = new School(1);

function School(id) {
  this.id = id;
  Unload_School();

  function Unload_School() {

    var div = document.createElement("div");
    div.id = "school";

    var h1 = document.createElement("h1");
    h1.id = "h1";
    h1.style.color = "red";

    var title = document.createTextNode("High School");
    h1.appendChild(title);

    // I use here but not work
    addEvent(document.getElementById("h1"), "click", new Function("edit(this)"));

    var h3 = document.createElement("h3");
    h3.style.color = "blue";

    var subtitle = document.createTextNode("List Of Students:");
    h3.appendChild(subtitle);

    div.appendChild(h1);
    div.appendChild(h3);

    document.body.appendChild(div);
  };
}

function addEvent(obj, evType, fn) {
  try {
    obj.addEventListener(evType, fn, false);
  } catch (e) {}
  try {
    obj.attachEvent("on" + evType, fn);
  } catch (e) {}
}

function edit(param) {
  var elem = param;
  var input = document.createElement("input");
  input.setAttribute("type", "text");
  input.setAttribute("value", elem.firstChild.nodeValue);
  removeChildren(elem);
  elem.appendChild(input);
  input.focus();
  input.select();
  addEvent(input, "blur", function() {
    removeChildren(elem);
    elem.appendChild(document.createTextNode(input.value));
  });
}

function removeChildren(param) {
  for (var i = 0, elem; elem = param.childNodes[i]; i++) {
    elem.parentNode.removeChild(elem);
  }
}
#school {
  display: inline-table;
  vertical-align: middle;
  text-align: left;
}

#h1 {
  font-size: 50px;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans - serif;
}
<!DOCTYPE html>
<html lang="pt-PT">

<head>
  <meta charset="UTF-8">
  <title>High School</title>
</head>

<body>
  <div id="school"></div>
</body>

</html>

Answer №1

To improve your code, modify

addEvent(getElementById("title"), "click", new Function("edit(this)"));
to
addEvent(document.getElementById("title"), "click", new Function("edit(this)"));
. Additionally, please note that there is no element with the ID of h1.

Answer №2

Remember this rule: When creating elements, always append them to the DOM before trying to access them.

Take a look at this functional fiddle

 div.appendChild(h1);
 div.appendChild(h3);
 document.body.appendChild(div);

Ensure that you have appended all elements before searching for any of them.

 addEvent(document.getElementById("h1"), "click", new Function("edit(this)"));

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

Can you provide a succinct explanation of what constitutes a well-defined "landing page"?

Could someone provide a clear and concise explanation of what exactly constitutes a landing page and how it should be utilized? I'm struggling to grasp the concept. Where is the optimal placement for a landing page on a website? Is it best placed o ...

Utilizing AngularJS with dual controllers within a single view

I recently started working on an angularJS web app using a purchased template that has all its controllers, routes, and directives in a single file called app.js. This is my first dive into angularJS and front-end development. Hoping to become a Full Stac ...

Iterate over each item in the select and include a blank option if either of the elements is missing

Having trouble with 2 drop down menus, select1 and select2. I select item1 from select1 and then click the OK button. But when the selected index is 0 (first option), I want to loop through the items of both drop downs. If the elements at the same index ( ...

Error animation on client-side validation not resetting correctly

Incorporated a form validation and error display system utilizing TransitionGroup for animations. The flag issueVisible manages the visibility of the error message, while determineField() aids in identifying the field related to the error. The issue arise ...

Providing static files in Express while utilizing mustache templates

I'm struggling to configure Express to serve a directory of static mustache files. I have an object with data like this: { a: 'Hello :)' b: 'Goodbye :(' } Along with two files: public/a.html <div>{{a}}</div> pu ...

Developing an interface that utilizes the values of an enum as keys

Imagine having an enum called status export enum status { PENDING = 'pending', SUCCESS = 'success', FAIL = 'fail' } This enum is used in multiple places and should not be easily replaced. However, other developers migh ...

When attempting to change the text in the textarea by selecting a different option from the dropdown list, the text is not updating

I am facing an issue with three multi-select dropdown lists. When a user selects options from these lists and then presses the submit button, the selected text should display in a textarea. However, if the user manually changes some text in the textarea ...

Creating a reusable field for reactive forms in Angular: A step-by-step guide

I need assistance with creating a versatile field component for reactive forms, but I am facing challenges in retrieving the value from the custom-input element. <form [formGroup]="form" (ngSubmit)="submit()"> <custom-input i ...

Using Express.js to Serve Static Content on a Dynamic Route

I am working with the app.js code below; app.use(express.static(__dirname + "/public")); app.use("/example", express.static(__dirname + "/public")); app.engine("html", require("ejs").renderFile); app.get("/", (req, res) => res.render("index.ejs")); a ...

What's the best way to update the value of a TextInput field?

Previously, I was updating the text input using local state. Here's an example: state = {name: ''} ... <AddEditFormInputs onChangeText={name => this.setState({ name })} textStateValue ...

Identifying Inactivity in Cordova Android Applications

Hey there! So, I've created a flashlight/torch app that can be found at the following link: https://github.com/Skelware/Fancy-Flashlight. This app utilizes a Cordova plugin available here: https://github.com/Skelware/Cordova-Flashlight. For now, my m ...

Is it possible to customize the color of the modal backdrop in layer v4 of the Material-UI library

I am struggling to modify the background color of an MUI V4 modal. Instead of getting a clean color, I am seeing a gray layer on top of the backdrop. Though this seems to be the default behavior, I want to remove it and target the shaded div directly rathe ...

issue encountered when implementing slick.js in angular 6

Trying to implement slick.js, a carousel framework, in an Angular project. Initially attempted 'npm install slick --save' and manually adding the downloaded files to scripts and styles JSON objects. When that failed, resorted to importing the C ...

Finding the index of a column based on a continuous sequence of values can be achieved by following these

Consider this sequence of numbers representing components on a page: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 Every set of 3 numbers makes up a page, with indexing restarting for each new page. Essentially, it follo ...

Generate a selection of complementary, triadic, and monochromatic color palettes using just one hex color code

My goal is to generate three unique color palettes based on a single hex/rgb value given by the user. The first palette will feature the complementary color of the initial input, followed by a full range of colors in subsequent palettes. I aim to expand be ...

The button fails to function properly following the initial successful loading of ajax data

var Update = { init: function(){ $('.find').on('click', function(e){ e.preventDefault(); var $this = $(this), $form = $('#searchForm'); BLC.ajax({ ...

Redux: The action was effectively triggered, but the state remained unformed

I'm currently working on a project to familiarize myself with Redux. I am using the Redux DevTools to monitor my two states: lists and todos. However, I am running into an issue where only todos are being displayed, despite trying various troubleshoot ...

Records are being loaded into the table, but the browser is unresponsive

After making an ajax call, I am receiving over 1000 tr elements for the tbody of a table. However, when I try to load this data into the tbody of the table, Loading the records into the tbody of the table becomes a problem. $('#loadingRecords') ...

The AJAX email submission form is not functioning properly

Recently, I have upgraded my email sign-up form on the website to include validation. However, after adding the validation, the form no longer sends and an error message is not displayed. Upon inspecting, I found the following error: TypeError: null is ...

Raycasting intersection with a line on BufferGeometry in Three.js

After successfully implementing raycasting on lines with R59 and displaying tooltips on mouseover, I encountered performance issues due to increasing data. This led me to switch from using THREE.Geometry to THREE.BufferGeometry. While everything else seems ...