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()这项工作做得很好。正如菲利克斯指出的那样,由于.contents()对所有文本(包括空格)都很敏感,如果内容发生变化,您必须相应地修改我的答案。

于 2013-06-08T18:39:31.450 回答
0

有很多方法可以做到这一点,具体取决于您的结构实际情况。

<span class="country">country1</span>span是元素内的第二个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 回答
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 回答