有一个插件可以在页面上生成一些 div,当它们被查看时,它会让它们显示:无,但所有这些都堆积得太多了。如何通过 Javascript 删除它们?
<div id="workarea">
<div id="message" class="messages" style="display: none;">Your message was saved</div>
<div id="message" class="messages" style="display: none;">Your message was saved</div>
<div id="message" class="messages" style="display: none;">Your message was saved</div>
<div id="message" class="messages" style="display: none;">Your message was saved</div>
</div>
现在我不能只做 $("workarea").innerHTML ="";
因为那时我在工作区需要更多的东西,还有元素(其他 div)在我想要保留的工作区中有 display:none
。最好的方法是我可以获取像“消息”这样的类,并让它找到所有具有 display:none
且具有类“消息”的 div,但是如何?
最佳答案
只需遍历它们并检查 style.display
以查看它是否为 "none"
:
// Reminder to lurkers: This is Prototype, not jQuery!
$("workarea").childElements().each(function(child) {
if (child.style.display === "none") {
$(child).remove();
}
});
或者,如果您想将其限制为具有 "messages"
类的 #workarea
的子元素:
// Reminder to lurkers: This is Prototype, not jQuery!
$("workarea").childElements().each(function(child) {
if (child.style.display === "none" && child.hasClassName("messages")) {
child.remove();
}
});
或者就此而言:
// Reminder to lurkers: This is Prototype, not jQuery!
$$("#workarea > .messages").each(function(child) {
if (child.style.display === "none") {
$(child).remove();
}
});
旁注:您引用的 HTML 无效。 id
值必须在文档中是唯一的,您不能有多个 div
具有 id
“消息”
。不会改变上面的答案,但我想我应该提一下。如果这些是由插件生成的,我建议使用不同的插件。 :-)
关于javascript - 删除属性显示为 :none via Javascript 的页面上的 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16483955/