jQuery - 根据类名删除 DIV

4

通过jQuery,是否可以删除页面上所有具有以下模式的DIV,并保留它们的内容?

<div class="ExternalClass85AC900AB26A481DBDC8ADAE7A02F039">....</div>

请注意,DIV遵循以下模式:
  • 类名始终以ExternalClass开头,但后面跟着另一个值,永远不会相同,

  • 并且DIV没有任何其他属性,只有class。 (这是在SharePoint上)

谢谢。

请注意,DIV 应该只有 class 属性,没有其他属性。提供的解决方案都很好,但是有人能否为这个问题提供一个补充呢? - Alex
1
让我笑了的是,这是我搜寻到的第一个结果,即使我的搜索或者你的原始帖子都没有提到,我完全意识到我们可能都因为SharePoint而遇到了这个问题?给这个好问题点赞。 - user1017882
1
很抱歉,我之前没有看到你的“这是在SharePoint上”的说明。 - user1017882
8个回答

4
是的,您可以使用属性开始选择器和replaceWith方法:(属性开始选择器)(replaceWith方法)
$('[class^="ExternalClass"]').filter(function() { 
  return this.attributes.length === 1; 
}). replaceWith(function() {
  return $(this).html();
});

@dfsq 说得好,以前的版本中避免再次创建 jQuery 对象是有用的,但是由于 replaceWith 在所有匹配的元素上都起作用,因此 each 调用是不必要的。 - Rich O'Kelly
所有这些答案都有一个问题:我需要删除那些只有class属性而没有其他属性的DIV。 - Alex
谢谢,Rich。为什么 return this.attributes.length === 1; 上有一个返回呢?再次感谢 :) - Alex
1
@Alex 这将过滤元素集,只保留具有一个属性(在本例中保证为 class 属性)的元素 - 如果是这种情况则返回 true,否则返回 false。请查看 jQuery Filter 方法以获取更多信息。 - Rich O'Kelly

2
$('[class^="ExternalClass"]').replaceWith(function() {
    return $(this).html();
});

谢谢,dfsq。请查看我的评论和要求的第二个要点:DIV应该只有类属性,没有其他属性。到目前为止,所有的答案都忽略了这一点。有人有解决方案吗? - Alex

1

您可以尝试使用属性开始选择器^=来实现此操作。

$('div[class^="ExternalClass"]').each(function(){
    $(this).replaceWith($(this).html());
});

1
var $text = ""; 
$.each($("div"), function(){
    $text = $text + this.html();
});
document.write($text);

1

示例 HTML:

<div class="ExternalClass85AC900AB26A481DBDC8ADAE7A02F039">foo</div>
<div class="ExternalClass85AC900AB26A481DBDC8ADAE7A02sdfsdsdfF039">bar</div>

示例Jquery:

$('div[class^="ExternalClass"]').each(function() {
  $(this).contents().unwrap();
});

输出:

foo bar

(没有div)

这是fiddle:

http://jsfiddle.net/6hbhL/


1

我的代码:

function unrichText(texto) {
  var n = texto.indexOf("\">"); //Finding end of "<div&nbsp;class="ExternalClass...">
  var sub = texto.substring(0, n+2); //Adding first char and last two (">)
  var tmp = texto.replace(sub, ""); //Removing it
  tmp = replaceAll(tmp, "</div>", ""); //Removing last "div"
  tmp = replaceAll(tmp, "<p>", ""); //Removing other stuff
  tmp = replaceAll(tmp, "</p>", "");
  tmp = replaceAll(tmp, "&#160;", "");
  return (tmp);
}

function replaceAll(str, find, replace) {
    return str.replace(new RegExp(find, 'g'), replace);
}

谢谢,@WalterDiBiase。干得好!非常不错的方法 :) 欢迎来到StackOverflow! - Alex

1

获取 div 中的内部 html。 获取父标签或前一个标签,将内容粘贴到其中或在删除 div 后粘贴。 Jquery 可能有一个替换函数,不确定哪个更容易。

应该可以使用 .remove() 来摆脱 div。

$("[class$='ExternalClass']").remove();
可能是 id*= 我忘记了哪一个。

Revised: http://api.jquery.com/replaceWith/


他们有上述功能,刚刚找到了它,看起来会起作用。 - Yogurt The Wise
选择的是ID,而不是类。 - Diodeus - James MacFarlane

1

你需要重新编写 HTML。

$("div [class^=ExternalClass]") 将选择元素。

获取 innerHTML,将其附加到元素后面,然后删除该元素。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接