显然,这是一个通用示例,我必须根据通用情况进行调整。
我想删除一个没有 ID 或类的 DOM 元素。我可以使用很多方法,但我想知道我是否可以不添加类(例如),JQuery 是否可以进行这种匹配。
做错了什么,或者不可能?
谢谢
很抱歉第一次发布这个问题,我正在覆盖 div 结果
$newTest
的结果是它没有删除最后一段 $last
。
$(document).ready(function() {
var $last = $('#test').children().last(); // Get a generic element
var $newTest = $('#test').clone(); // Clone my DOM elements
$newTest.find($last).remove();
// Find and remove the element!
// This does not work!
$('#result').html($newTest.html() + '<hr>' + $last.html());
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test">
<p>freddy</p>
<p>fred</p>
<p>freddyx</p>
<p>freddy</p>
</div>
<hr>
<div id="result">
</div>
最佳答案
我认为您尝试做的事情的问题在于 .clone()
Description: Create a deep copy of the set of matched elements.
这里的关键词是深层复制,意思是$newTest
中的所有内容都不同于#test
。 AFAIK,这意味着您保存为指针的变量 $last
无法在 $newTest
中找到。 $last
元素在那里不存在。
可能的解决方案?
我不知道这是否适用于您的用例,但由于您已经有一些任意选择器,您可以保存该选择器并使用 eval()
将该选择器应用于克隆对象:
$(document).ready(function() {
var $last = $($('#test').children().last()); // Get a generic element
var selector = '.children().last()';
var $newTest = $('#test').clone(); // Clone my DOM elements
$newTest.find(eval('$newTest' + selector)).remove();
// Find and remove the element!
// This does not work, $newTest is empty!
$('#result').html($newTest);
$('#result2').html('<hr>' + $last.html());
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test">
<p>freddy</p>
<p>fred</p>
<p>freddyx</p>
<p>freddy</p>
</div>
<hr>
<div id="result">
</div>
<hr>
<div id="result2">
</div>
关于javascript - 查找并删除通用元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46649026/