4

コードは次のとおりです。

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

これに変更したいのですが:

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

子要素を削除してラップされていないテキストを保持する方法を尋ねる人がたくさんいますが、その逆はありません。名前のないものをどのようにターゲットにしますか?

4

4 に答える 4

7

これを試して:

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

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

フィドル: http: //jsfiddle.net/maniator/t2CDk/

これを行うevent listenersと、要素からのデータが失われます。

于 2011-04-15T17:20:30.683 に答える
0

これは昔ながらのJavaScriptの方法で実行でき、各ノードでnodeTypeが3であるかどうかをテストしてから、removeChildを実行します。これは非常にクリーンで迅速(最小限のjQuery)であり、イベントリスナーを混乱させることはありません。

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 );
}
于 2011-04-15T17:35:44.737 に答える
0

Nealsの回答を変更して、複数の要素で機能するようにしました。

$( elements ).each(function() {  
var child = $(this).children();  
$(this).html(child);   
});
于 2013-02-21T20:45:23.447 に答える
0

非常に簡単なのは、次のコードを使用するだけです。

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");  

    });
});

完全な例は次のとおりです:https ://blog.hfarazm.com/remove-unwrapped-text-jquery/

于 2018-04-17T16:26:30.297 に答える