<div class="parentDiv" >
<button class="close"
data-dismiss="modal"
style="..."
aria-label="Close"
onclick='$(this).closest(".parentDiv").remove()'
>
<span class="glyphicon glyphicon-remove-circle small"></span>
</button>
<div class="alert alert-danger">{{ errorMsg }}</div>
</div>
...
...
在上面的示例代码中,我可以使用什么策略将jQuery $(this)更改为纯JavaScript代码,例如使用querySelector?
请注意,我要使用Element.closest(),因为会有很多Div元素彼此堆叠在一起,具有“ parentDiv”类名称。
基本上,我想选择父节点,然后单击$(this)元素后删除该节点。
那么在不使用$(this).closest('。parentDiv')。remove()之类的jQuery选择器的情况下执行此操作的最佳方法是什么?
并且可以在不知道当前元素(this)的类名或ID的情况下执行此操作吗?
最佳答案
如果按钮始终嵌套在parentDiv
容器中,只需抓住父节点并使用parentNode
和remove
将其删除。
document.querySelector("button").addEventListener("click", function() {
this.parentNode.remove();
});
<div>
<button>remove me</button>
</div>
在一个onclick中:
<div>
<button onclick="this.parentNode.remove()">remove me</button>
</div>
关于javascript - 如何使用querySelector选择此元素,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48291048/