Iqbal Perkasa
Iqbal Perkasa

Reputation: 31

jQuery .before with same id

i just want to ask about jQuery. Can jQuery do this:

<h1 id="lorem-ipsum">Hello World!</h1>

to this:

<div id="lorem-ipsum"></div>
<h1>Hello World!</h1>

Upvotes: 0

Views: 68

Answers (3)

Ram
Ram

Reputation: 144699

Try the following:

var txt = $('#lorem-ipsum').text()
$('#lorem-ipsum')
    .after($('<h1/>').text(txt))
    .replaceWith('<div id="#lorem-ipsum"/>')

DEMO

Upvotes: 1

Tats_innit
Tats_innit

Reputation: 34107

You mean like this man: working demo Bit dynamic version: http://jsfiddle.net/QSdqM/ or http://jsfiddle.net/GQzFU/

Hope it helps the cause :)

API: http://api.jquery.com/replaceWith/

code

$('h1').replaceWith(function() {

   return '<div id="' + this.id + '"></div><h1>' + $(this).text() + '</h1>'

});

OR

$('h1').replaceWith('<div id="lorem-ipsum"></div><h1>Hello World!</h1>');


alert($('body').html());​

Upvotes: 3

Bali Balo
Bali Balo

Reputation: 3408

var myDiv = $('<div></div>').attr('id', 'lorem-ipsum');
$('h1#lorem-ipsum').removeAttr('id').before(myDiv);

Upvotes: 1

Related Questions