DEV Community

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

Posted on

5 1

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! 😊😊

SurveyJS custom survey software

Simplify data collection in your JS app with a fully integrated form management platform. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more. Integrates with any backend system, giving you full control over your data and no user limits.

Learn more

Top comments (2)

Collapse
 
utsavladani profile image
Utsav Ladani

Good idea 👍

Collapse
 
walternascimentobarroso profile image
Walter Nascimento

thanks ;)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs