Exchanging TAG with Javascript

Asked

Viewed 1,993 times

2

Is there a way in JS/Jquery to change a tag in HTML?

For example, I have a:

<div></div>

And I want, let’s say I want it to become a span:

<span></span>

In short, to change:

<div></div>

For:

<span></span>

Or for any other tag, is it possible? For example, use a remove() and then an Insert but the Insert tag is in the same place as the tag I removed.

  • 3

    Of course this is impossible. Once an element has been created, it is immutable. Most likely any and all way to do this will be a scam and will be subject to failures.

3 answers

7


Changing the widget itself is not possible. But you can change the HTML if you don’t need event headphones.

You can do it with a few steps:

  • creates a new element
  • put it before the element you have
  • changes the content to the new
  • erases the old one

var novo = $('<div/>');
var antigo = $('span');
antigo.before(novo);
novo.append(antigo.children());
antigo.remove();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span>
  <p>Olá!</p>
</span>

  • Thank you all, but I like Sergio’s idea, "creates a new element puts it before the element you have changes the content to the new deletes the old one", it worked out, thank you very much!

3

As @jbueno commented, changing the tag itself is impractical, the closer we can get to that would be something like:

$('div').click(function() {
   $(this).replaceWith($('<section style="border:1px solid red;" >' + this.innerHTML + '</section>'));
});

$('span').click(function() {
   $(this).replaceWith($('<h2>' + this.innerHTML + '</h2>'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="border:1px solid green;">
  div
</div>

<span>teste</span>

1

I’m not sure about changing the tag, but you can add an Hidden class and remove another Hidden class with addClass() and removeClass() from jQuery.

Ex:

<div style="hidden" id="divescondida">...</div>
<span style="" id="spanamostra">...</span>

<script>
  $("#divescondida").removeClass("hidden");
  $("#spanamostra").addClass("hidden");
</script>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.