删除除子项之外的所有内容


<div class="parent">
   <span>sometext</span>
   plain text
   <input class="child">
</div>
<div class="parent">
   <span>sometext</span>
   plain text
   <input class="child">
</div>
<div class="parent">
   <span>sometext</span>
   plain text
   <input class="child">
</div>

如何安全地删除.parent中除.child之外的所有内容?

我使用的是这个代码(其中items.child的堆栈,each.child(

items.each(function(){
    $(this).parent().children().each(function(){
       if ($(this).hasClass('child'))
          // do something
       else
          $(this).remove();
    });
    $(this).unwrap(); // remove parent, keep only .child
});

但它不能处理纯文本。

你说过

.parent中可以有多个.child,我们只保留第一个。所以如果有三个,第二个和第三个应该去掉。

以及

items.child的堆栈,每个是.child

好吧,那么这就是我要做的:

items.parent('.parent').each(function() {
    var parent = $(this),
        child  = parent.children('.child').first();
    child.detach();
    parent.empty().append(child);
});

它的作用:

  1. .child元素的集合上移到.parent元素的集合。生成的集合将仅具有唯一的父对象。

  2. 在父母之间循环。

  3. 获取每个父级中的第一个.child并将其分离。

  4. 清空.parent

  5. 重新连接.child

最终结果是,每个.parent将只有一个.child(并且没有其他子级,无论是否为.child(。

这里有一个纯JS的解决方案:fiddle

因此,在您的循环中,您可以使用以下内容:

this.parentNode.innerHTML = this.outerHTML;

如果您必须保留附加的事件处理程序:

var _this = this.cloneNode(true),
    parent = this.parentNode;
parent.innerHTML = '';
parent.appendChild(_this);

这样的东西就可以了;

$('.parent').on('click', '.child', function(e) {
    var $this = $(this),
        $parent = $this.parent(),
        $children = $parent.find('.child'); // or: $this.siblings('.child');
    $parent
        .empty() // Empty the "parent" element
        .append($children); // Re-append all "child" element to "parent"
    $this.focus(); // Focus the (input) element
});

这里有一个使用正则表达式的替代方案:

$('.parent').each(function() {
    $(this).html($(this).html().match("<input class=.child.>"));
});

最新更新