我想指定要保留的元素,但要保留其结构。 示例:
<html>
<head>
<meta xx>
</head>
<body>
<div class="some1">
<div class="some1-1"></div>
<div class="some1-2"></div>
<div class="some1-3"></div>
<div class="some1-4"></div>
<div class="some1-5"></div>
</div>
<div class="some2">
<div class="some2-2">
<div class="some2-2-1"></div>
<div class="some2-2-2"></div>
</div>
<div class="some2-3"></div>
<div class="some2-4"></div>
<div class="some2-5"></div>
</div>
</body>
</html>
例如,我只需要保持: .some2-2-1,.some-2-3,.some-1-3,删除所有其他元素,并保留其父元素,这样它将是:
<html>
<head>
<meta xx>
</head>
<body>
<div class="some1">
<div class="some1-3"></div>
</div>
<div class="some2">
<div class="some2-2">
<div class="some2-2-1"></div>
</div>
<div class="some2-3"></div>
</div>
</body>
</html>
我不能指定要删除的元素(它是动态的),而只能指定要保留的元素,如何实现?
$('*:not('.some2-2-1, .some-2-3, .some-1-3')').remove()
在那种情况下是行不通的;)
答案 0 :(得分:0)
我敢肯定会有几种方法,但这是一种方法(请参阅评论):
$(function() {
var elementsToKeep = [
".some2-2-1",
".some2-3",
".some1-3",
];
// parent elements that are needed will be appended here
var needed = [];
for (var i = 0; i < elementsToKeep.length; i++) {
// get the hierarchy, e.g. ".some2-2-1" -> "2-2-1"
var hierarchyPos = elementsToKeep[i].replace(".some", "");
// if we're keeping 2-2-1, we also need 2-2, and 2
//
// recursively remove the last two characters to get
// the parent level until there's nothing left
while (hierarchyPos !== "") {
if (!needed.includes(hierarchyPos)) {
needed.push(hierarchyPos);
}
hierarchyPos = hierarchyPos.slice(0, -2);
}
}
// "needed" will now contain 2-2-1, 2-2, 2, etc.
console.log("all required elements:", needed.join(", "));
// iterate through each of the original selectors
$(elementsToKeep.join(",")).each(function() {
// check each of this element's siblings and remove
// any whose class isn't included in the "needed" array
var siblings = $(this).siblings();
siblings.each(function(i, el) {
var pos = el.className.replace("some", "");
// if "pos" is 2-2-2 (for example), it won't appear in "needed",
// so it's safe to remove
if (!needed.includes(pos)) {
$(el).remove();
}
})
})
// finished
console.log("final output:");
console.log($("#test").html());
})
<div id="test">
<div class="some1">
<div class="some1-1"></div>
<div class="some1-2"></div>
<div class="some1-3"></div>
<div class="some1-4"></div>
<div class="some1-5"></div>
</div>
<div class="some2">
<div class="some2-2">
<div class="some2-2-1"></div>
<div class="some2-2-2"></div>
</div>
<div class="some2-3"></div>
<div class="some2-4"></div>
<div class="some2-5"></div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>