Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: how to change tag name?

jQuery: how to change tag name?

For example:

<tr>     $1 </tr> 

I need

<div>     $1 </div> 

Yes, I can

  1. Create DOM element <div>
  2. Copy tr content to div
  3. Remove tr from dom

But can I make it directly?

PS:

    $(tr).get(0).tagName = "div";  

results in DOMException.

like image 600
puchu Avatar asked Aug 08 '10 20:08

puchu


People also ask

How do I change a tag name?

Choose the Tag you want to rename. Right-click on it and choose Rename to rename the Tag. You can also click on the name of the Tag to rename quickly. Change the name from the colors to anything you like and hit Enter.

How do I edit a tag in JavaScript?

To change the element tag name in JavaScript, simply need to make a new element and move over all the elements so you keep onclick handlers and such, and then replace the original thing.


1 Answers

You can replace any HTML markup by using jQuery's .replaceWith() method.

example: http://jsfiddle.net/JHmaV/

Ref.: .replaceWith

If you want to keep the existing markup, you could use code like this:

$('#target').replaceWith('<newTag>' + $('#target').html() +'</newTag>') 
like image 143
jAndy Avatar answered Sep 21 '22 10:09

jAndy