RGBK
RGBK

Reputation: 2048

jQuery — Remove unwrapped text but preserve the elements?

So here's the code:

<parent><child>i want to keep the child</child>Some text I want to remove</parent>

I'd like to change it to this:

<parent><child>i want to keep the child</child></parent>

I see lots of people asking how to remove the child element and preserve the unwrapped text, but not the other way around. How do you target something that isn't named?

Upvotes: 4

Views: 4119

Answers (4)

hfarazm
hfarazm

Reputation: 1417

Very simple just use this code:

jQuery(function($){

    // Replace 'td' with your html tag
    $("td").html(function() { 

    // Replace 'ok' with string you want to change, you can delete 'hello everyone' to remove the text
          return $(this).html().replace("ok", "hello everyone");  

    });
});

Here is full example: https://blog.hfarazm.com/remove-unwrapped-text-jquery/

Upvotes: 0

James
James

Reputation: 1

I modified Neals answer so it works for multiple elements:

$( elements ).each(function() {  
var child = $(this).children();  
$(this).html(child);   
});

Upvotes: 0

Groovetrain
Groovetrain

Reputation: 3325

You can do it the ol' fashioned javascript way, and test each node for the nodeType of 3, then do a removeChild on it. This would be pretty clean and quick (minimal jQuery), and wouldn't mess up any event listeners.

var parent = $('parent')[0];  // Get reference to DOM

for( var i = 0; i < parent.childNodes.length; i++ ) {
  var current_child = parent.childNodes[i];
  if( current_child.nodeType == 3 )
    parent.removeChild( current_child );
}

Upvotes: 0

Naftali
Naftali

Reputation: 146320

try this:

var child = $('parent').children('child');

$('parent').html(child);

fiddle: http://jsfiddle.net/maniator/t2CDk/

if you do this you lose any event listeners and data from the elements.

Upvotes: 7

Related Questions