DEV Community

Cover image for Convert span to input and vice versa, using javascript
Walter Nascimento
Walter Nascimento

Posted on

Convert span to input and vice versa, using javascript

[Clique aqui para ler em português]

let’s convert a span to an input using javascript and an input to a span.

Code

First we will create the interface, we will do something simple, using only HTML.

<div id="element">
  <span onclick="spanSwitch(this)"> John </span>
</div>
Enter fullscreen mode Exit fullscreen mode

We have a div with id element to assist in the search with javascript, we have a span that calls a function when clicking.

function spanSwitch(e) {
  let txt = e.innerText;
  let element = document.getElementById('element');

  element.innerHTML = `<input onblur='spanReset(this)' value='${txt}' />`;
  document.getElementsByTagName('input')[0].focus();
}

function spanReset(e) {
  let txt = e.value;
  let element = document.getElementById('element');

  element.innerHTML = `<span onclick='spanSwitch(this)'> ${txt} </span>`;
}
Enter fullscreen mode Exit fullscreen mode

We have two functions:

  • *spanSwitch = Here the span is replaced by the input, using the span text as the input value;
  • *spanReset = Here the input is replaced by the span, using the input value as the span text;

ready as simple as that.

Demo

See the complete project working below.

Youtube

If you prefer to watch, I see the development on youtube (video in PT-BR).


Thanks for reading!

If you have any questions, complaints or tips, you can leave them here in the comments. I will be happy to answer!

😊😊 See you! 😊😊

Oldest comments (2)

Collapse
 
utsavladani profile image
Utsav Ladani

Good idea 👍

Collapse
 
walternascimentobarroso profile image
Walter Nascimento

thanks ;)