Canna
Canna

Reputation: 3794

How can i empty the element except one element in jQuery?

Example,

 <td id="example">
   Something is inside here.
   <button id="paymentBtn">pay</button>
 </td>

What i want to do is, "only emtpy" before payment button and insert a new thing like this,

<td id="example">
   Deleted old one, and inserted new one.
   <button id="paymentBtn">pay</button>
 </td>

I know i can use

$("#paymentBtn").before("inserted new one");

but how can i empty?

If i empty example. it blows everything and

 $("#paymentBtn").before().empty(); 

This doesn't work :(

Upvotes: 3

Views: 588

Answers (3)

m1k1o
m1k1o

Reputation: 2364

One of the andwer is, store the text into the <span class="deleteThis"></span>

 <td id="example">
   <span class="deleteThis"> Something is inside here.</span>
   <button id="paymentBtn">pay</button>
 </td>

And remove it, or rewrite with some other text:

$("#paymentBtn").parent().find(".deleteThis").empty().html("Changed"); 

Or navigate right from parent:

$("#example .deleteThis").empty().html("Changed"); 

Second answer is, that you can remove everything but one element:

var oldElem = $("#paymentBtn").clone();
$('#example').empty().append("Deleted successfully.").append(oldElem);

You clone the element/s you donot want to remove, empty parent and restore cloned element/s.

Upvotes: 0

AdityaSaxena
AdityaSaxena

Reputation: 2157

i'd ideally have my html like this..where text is not directly inside :

<td id="example">
   <span>Something is inside here.</span>
   <button id="paymentBtn">pay</button>
 </td>

Then I'd want my html to be this later:

<td id="example">
   <span>Deleted old one, and inserted new one.</span>
   <button id="paymentBtn">pay</button>
 </td>

And, then I will do this:

$('#example').find('span').html('Deleted old one, and inserted new one.');

Or this, $('#paymentBtn').prev().html('Deleted old one, and inserted new one.');

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388316

Try

$($("#paymentBtn").get(0).previousSibling).remove();

Demo: Fiddle

As suggested also you can

$('#add').click(function(){
    $("#paymentBtn").before("<span>inserted new one</span>");
})
$('#remove').click(function(){
    $("#paymentBtn").prev('span').remove();
})

Demo: Fiddle

Upvotes: 2

Related Questions