如何用原生JavaScript移除两个meta标签间的所有<link>标签
移除两个Meta标签间所有Link标签的实现方案
现有HTML结构中,多个<link>样式标签被包裹在两个特定的<meta>标签之间,结构如下:
<meta id="front-template-css-anchor-start" name="front-template-css-anchor-start" content="This is where front template css will be added"/> <link rel="stylesheet" href="%PUBLIC_URL%/front-template/assets/css/bootstrap.min.css" /> <link rel="stylesheet" href="%PUBLIC_URL%/front-template/assets/css/LineIcons.2.0.css" /> <link rel="stylesheet" href="%PUBLIC_URL%/front-template/assets/css/animate.css" /> <link rel="stylesheet" href="%PUBLIC_URL%/front-template/assets/css/tiny-slider.css" /> <link rel="stylesheet" href="%PUBLIC_URL%/front-template/assets/css/glightbox.min.css" /> <link rel="stylesheet" href="%PUBLIC_URL%/front-template/assets/css/main.css" /> <meta id="front-template-css-anchor-end" name="front-template-css-anchor-end" content="This is where front template css will be added"/>
已通过以下代码获取到两个锚点Meta元素:
var frontTemplateCssAnchorStart = document.querySelector('#front-template-css-anchor-start'); var frontTemplateCssAnchorEnd = document.querySelector('#front-template-css-anchor-end');
仅使用frontTemplateCssAnchorEnd.previousElementSibling.remove()只能删除最后一个<link>,以下是批量移除两个锚点间所有<link>标签的可行方案:
方案一:遍历锚点间元素逐个删除
从起始锚点的下一个元素开始遍历,直到遇到结束锚点为止。为避免删除当前元素后丢失后续节点引用,需先缓存下一个元素:
let currentEl = frontTemplateCssAnchorStart.nextElementSibling; while (currentEl && currentEl !== frontTemplateCssAnchorEnd) { const nextEl = currentEl.nextElementSibling; currentEl.remove(); currentEl = nextEl; }
方案二:利用父元素批量处理
若两个锚点标签拥有共同父元素,可通过父元素的子元素集合筛选出锚点间的元素并批量删除:
const parentEl = frontTemplateCssAnchorStart.parentElement; const children = Array.from(parentEl.children); const startIndex = children.indexOf(frontTemplateCssAnchorStart); const endIndex = children.indexOf(frontTemplateCssAnchorEnd); // 截取锚点之间的元素并逐个移除 children.slice(startIndex + 1, endIndex).forEach(el => el.remove());
两种方案均可实现需求,第一种更直接高效,第二种适合需要对锚点间元素做批量预处理的场景。
内容的提问来源于stack exchange,提问作者Saswat
相关产品推荐
相关产品推荐

