# Editing a single element in JavaScript

Now we will learn how to edit element texts using input fields. Let's start with simple things and gradually get more complex.

So, let's say we have a paragraph and an input located in the same parent:

`<div id="parent"> <p id="elem">text</p> <input id="input"> </div>`

Let's make it so that when the focus is lost in the input, its text appears in the paragraph:

`let elem = document.querySelector('#elem'); let input = document.querySelector('#input'); input.addEventListener('blur', function() { elem.textContent = this.value; });`

Let's now make it so that when you enter the page, the input already contains the text of the paragraph. Thus, using the input, we will be able to edit the text located in the paragraph.

Let's implement:

`let elem = document.querySelector('#elem'); let input = document.querySelector('#input'); input.value = elem.textContent; // writes the paragraph text to the input input.addEventListener('blur', function() { elem.textContent = this.value; });`

Modify the code above so that the paragraph text doesn't change when focus is lost, but as text is entered into the input.

## Appearance of input

Let's now make it so that the input was not initially on the page, but it appeared when clicking on the paragraph. So our initial HTML will look like this:

`<div id="parent"> <p id="elem">text</p> </div>`

To begin with, we simply implement the appearance of the input, without editing:

`let elem = document.querySelector('#elem'); elem.addEventListener('click', function() { let input = document.createElement('input'); input.value = elem.textContent; elem.parentElement.appendChild(input); });`

And now let's make it so that when the focus is lost in the input, the text of the paragraph changes:

`let elem = document.querySelector('#elem'); elem.addEventListener('click', function() { let input = document.createElement('input'); input.value = elem.textContent; input.addEventListener('blur', function() { elem.textContent = this.value; }); elem.parentElement.appendChild(input); });`

Our code, however, is not perfect, since each click on a paragraph will result in a new input.

To solve the problem, we will simply remove the current input by losing focus:

`let elem = document.querySelector('#elem'); elem.addEventListener('click', function() { let input = document.createElement('input'); input.value = elem.textContent; input.addEventListener('blur', function() { elem.textContent = this.value; this.remove(); // removes the input }); elem.parentElement.appendChild(input); });`

On your own, without looking into my code, solve the described problem.

← →
↑
en ru