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

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (2)

Collapse
 
utsavladani profile image
Utsav Ladani

Good idea 👍

Collapse
 
walternascimentobarroso profile image
Walter Nascimento

thanks ;)

nextjs tutorial video

Youtube Tutorial Series 📺

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series