我正在尝试创建“ onclick”功能,以仅删除特定标签的较近元素!
例如:
<div>
<video src="path/video.mp4"></video>
<div>This div must be removed</div>
<div>Controls</div>
</div>
在这种情况下,我必须搜索页面中的所有标签“ video”并仅删除下一个div(“必须删除此div”)。并保持div具有“控件”。所以我必须得到这个结果:
<div>
<video src="path/video.mp4"></video>
<div>Controls</div>
</div>
我做事的方式让我失去了一切:
function remove() {
var videos = document.getElementsByTagName("video");
for (var i=0;i<videos.length;i+=1){
var classe = videos[i].getAttribute("class");
parentDiv = videos[i].parentNode;
var classParent = parentDiv.getAttribute("class");
var arrayClassParent = classParent.split(' ');
var classParent = arrayClassParent[0];
var divVideo = document.getElementsByClassName(classParent)[0];
var cntnt = document.getElementsByClassName(classParent)[i];
while (cntnt.childNodes.length > 1) {
cntnt.removeChild(cntnt.lastChild);
}
}
}
注意:div类和ID是设置变量。所以我可以使用ID和类来调用它们...
答案 0 :(得分:1)
也许您可以使用nextElementSibling
字段直接访问和删除文档中每个video
之后的元素?因此,类似的方法可能对您有用:
function removeElementNextToVideo() {
// Query for all video elements in document
for(const video of document.body.querySelectorAll('video')) {
// For each video, check for and remove the element directly
// after (next) to it
if(video.nextElementSibling) {
video.nextElementSibling.remove();
}
}
}
removeElementNextToVideo();
<div>
<video src="path/video.mp4"></video>
<div>This div must be removed</div>
<div>Controls</div>
</div>
此外,如果仅当它是DIV时要删除下一个元素,则可以执行以下操作:
function removeDivNextToVideo() {
// Query for all video elements in document
for(const video of document.body.querySelectorAll('video')) {
// For each video, check for and remove the element directly
// after (next) to it only if the element is a DIV
if(video.nextElementSibling && video.nextElementSibling.tagName === 'DIV') {
video.nextElementSibling.remove();
}
}
}
removeDivNextToVideo();
<div>
<video src="path/video.mp4"></video>
<h4>H4 directly after video, so nothing gets removed</h4>
<div>This div must be removed</div>
<div>Controls</div>
</div>
答案 1 :(得分:0)
在现代浏览器中,您可以使用带有Adjacent sibling combinator 1
的选择器来选择紧随视频元素之后的div元素,例如
video + div
function removeDivs() {
document.querySelectorAll('video + div').forEach(div => div.parentNode.removeChild(div));
}
video {height: 10px; border: 1px solid red;}