Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you replace an HTML tag with another tag in jquery?

Tags:

html

jquery

tags

I have a site I'm working on and it uses 'aside' tags, which I'm not getting IE8 to be able to read no matter what I try, even with an HTML5 Shiv. So, I'm wondering, how would you replace existing tags with other tags with jQuery?

For example, if I wanted to change

<aside>
  <h3></h3>
</aside>

to

<div>
  <h3></h3>
</div>

How would that be done?

like image 606
Paul L Avatar asked Apr 29 '13 18:04

Paul L


People also ask

How do you replace an element with another in jQuery?

To replace a DOM element with the specified HTML or DOM elements using jQuery, use the replaceWith() method. The replaceWith (content) method replaces all matched elements with the specified HTML or DOM elements. This returns the JQuery element that was just replaced, which has been removed from the DOM.

How do you replace a content of a tag with JavaScript?

Using JavaScript The most common approach to replace the content inside an element is with the innerHTML property. Alternatively, you can use the textContent to set the element's text content, which is considered safe against XSS attacks.


2 Answers

Try this:

$('aside').contents().unwrap().wrap('<div/>');
  • Get the contents of aside first.
  • Now unwrap the contents.
  • Now simply, wrap the contents inside a new tag, here a div.

DEMO


Also, you can do this using .replaceWith() method like:

$('aside').replaceWith(function () {
    return $('<div/>', {
        html: $(this).html()
    });
});

DEMO

like image 143
palaѕн Avatar answered Oct 25 '22 12:10

palaѕн


$('aside').replaceWith('<div><h3></h3></div>');
like image 40
Memolition Avatar answered Oct 25 '22 12:10

Memolition