[英]How to remove all the elements with null id
我想检查id没有值的页面上的ANY元素,然后使用jQuery的remove()
删除它们。
当ID没有从CMS传递的值时,它是这样的:
<iframe id class="iframeCol"...></iframe>
<div id class="sectional">..</div>
如何定位ID像上面一样的所有元素?
您可以使用属性选择器来实现:
$('[id=""]').remove();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <iframe id class="iframeCol">Remove this</iframe> <div id class="sectional">And remove this</div> <div>Keep this</div> <div id="foo">And this</div>
不用jQuery也可以做到:
Array.prototype.forEach.call(document.querySelectorAll('[id=""]'), function(node) {
node.parentNode.removeChild(node);
});
我知道您指定了jQuery的用法,但此处仅供参考。
$('body *').each(function() { console.log($(this).attr('id')) if ($(this).attr('id') == '') { $(this).remove(); } })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <iframe id class="iframeCol" ...></iframe> <div id class="sectional">..</div> <div class="sectional">123</div> <div id='asd' class="sectional">asd</div>
比较ID(如果等于空白则删除)
如果您喜欢没有jQuery的普通JavaScript,则可以使用以下代码:
document.querySelectorAll('[id=""]').forEach(function(item){ item.parentNode.removeChild(item); });
<iframe id class="iframeCol">Remove this</iframe> <div id class="sectional">And remove this</div> <div>Keep this</div> <div id="foo">And this</div>
简要说明:
Document.querySelectorAll()使用CSS3选择器选择元素列表。
Array.prototype.forEach()循环进行选择。
HTML DOM parentNode属性获取父节点的节点。
Node.removeChild()从DOM中删除一个子节点。
//Alternate way
$('body').find('*[id=""]').remove();
var removedItems = $('iframe, div') .map( function(){ if($(this).attr('id') == "") return this} ) .remove() .toArray(); console.log("See the removed items"); console.log(removedItems);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <iframe id class="iframeCol">Remove this</iframe> <div id class="sectional">And remove this</div> <div>Keep this</div> <div id="foo">And this</div> <div id="">Remove this</div>
@Rory McCrossan:谢谢您的摘录。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.