2

次の HTML がありますが、手動で変更できません。

<p class="class_1">
    <span class="support">Phonenr:</span> 
    1231231231 <span class="country">country1</span><br>
    312313123 <span class="country">country2</span><br>
    31231312 <span class="country">country3</span><br>
</p>

この部分を削除したい:

<span class="country">country1</span><br>
312313123 <span class="country">country2</span><br>
31231312 <span class="country">country3</span><br>

結果は次のようになります。

<p class="class_1">
    <span class="support">Phonenr:</span> 
    1231231231
</p>
4

3 に答える 3

10

試す:

$('p.class_1').contents(':gt(2)').remove();

jsFiddle の例

なぜこれが機能するのかについて簡単な説明を追加すると、.contents()要素だけでなく、テキスト ノードやコメント ノードも返されます。あなたの例では、 .contents()12個の要素が含まれています:

0: text (a newline)
1: span.support
2: text (1231231231 )
3: span.country
4: br
5: text (312313123 )
6: span.country
7: br
8: text (31231312 )
9: span.country
10: br
11: text (a newline)

ノード 2 の後にすべてを取り除きたいので.contents(':gt(2)').remove()、仕事はうまくいきます。Felix が指摘したように、.contents()スペースを含むすべてのテキストに敏感であるため、コンテンツが変更された場合は、それに応じて私の回答を変更する必要があります。

于 2013-06-08T18:39:31.450 に答える
0
var node = $('.class_1 span').get(1); // get the second span
parent = node.parentNode;
var sibling;
while (sibling = node.nextSibling){ // remove the nodes
    parent.removeChild(node);
    node = sibling;
}

http://jsfiddle.net/PGKW2/

于 2013-06-08T18:38:45.130 に答える
0

実際の構造に応じて、これを行うには多くの方法があります。

<span class="country">country1</span>span要素内の 2 番目のp要素です。

したがって、このノードとそれに続くすべてのノードを要素から削除できます。

$('p.class_1').each(function() {
    var $children = $(this).contents();
    var span = $children.filter('span').get(1);
    $children.slice($children.index(span)).remove();
});

デモ

于 2013-06-08T18:40:17.157 に答える