Jquery删除innertext但保留html

Okk*_*kky 10 javascript jquery dom

我有类似的东西.

<div id="firstDiv">
    This is some text
    <span id="firstSpan">First span text</span>
    <span id="secondSpan">Second span text</span>
</div>
Run Code Online (Sandbox Code Playgroud)

我想删除' 这是一些文本 '并且需要完整的html元素.

我试过用类似的东西

$("#firstDiv")
    .clone()    //clone the element
    .children() //select all the children
    .remove()   //remove all the children
    .end()  //again go back to selected element
    .text("");
Run Code Online (Sandbox Code Playgroud)

但它没有用.

有没有办法获得(并可能通过.text(""))标签内的自由文本,而不是其子标签中的文本删除?

非常感谢.

ade*_*neo 7

过滤掉文本节点并将其删除:

$('#firstDiv').contents().filter(function() {
    return this.nodeType===3;
}).remove();
Run Code Online (Sandbox Code Playgroud)

小提琴

要同时过滤文本本身,您可以:

$('#firstDiv').contents().filter(function() {
    return this.nodeType === 3 && this.nodeValue.trim() === 'This is some text';
}).remove();
Run Code Online (Sandbox Code Playgroud)

并获得文字:

var txt = [];

$('#firstDiv').contents().filter(function() {
    if ( this.nodeType === 3 ) txt.push(this.nodeValue);
    return this.nodeType === 3;
}).remove();
Run Code Online (Sandbox Code Playgroud)


MaV*_*SCy 2

看看这个小提琴

假设你有这个html

<parent>
  <child>i want to keep the child</child>
  Some text I want to remove
  <child>i want to keep the child</child>
  <child>i want to keep the child</child>
</parent>
Run Code Online (Sandbox Code Playgroud)

然后你可以像这样删除父级的内部文本:

var child = $('parent').children('child');
$('parent').html(child);
Run Code Online (Sandbox Code Playgroud)

检查这个小提琴以获取 html 的解决方案

var child = $('#firstDiv').children('span');
$('#firstDiv').html(child);
Run Code Online (Sandbox Code Playgroud)

PS:请注意,当您删除然后重新创建元素时,该 div 上绑定的任何事件处理程序都将丢失

  • 同时,您再次创建所有元素,因此所有数据、事件处理程序等都将丢失。 (3认同)