Exchanging TAGs with JavaScript

2

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

For example, I have one:

<div></div>

And I want, let's assume I want it to turn a span:

<span></span>

In short, change:

<div></div>

By:

<span></span>

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

    
asked by anonymous 22.05.2017 / 14:53

3 answers

7

Changing the element itself is not possible. But you can change the HTML if you do not need event headphones.

You can do this with a few steps:

  • creates a new element
  • put it before the element you have
  • change content to new
  • delete old

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>
    
22.05.2017 / 15:06
3

As @jbueno commented, changing the tag itself is impractical, the closest we can get to it 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><divstyle="border:1px solid green;">
  div
</div>

<span>teste</span>
    
22.05.2017 / 15:05
1

I'm not sure about changing the tag, but you can add a hidden class and remove another hidden class with jQuery addClass () and removeClass ().

Ex:

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

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