试图找出如何使用纯 js 来做到这一点,因此 jquery 不是一个选择。
假设我想抓取 div 中的所有段落标签,并在每个不包含单个图像或其他条件的段落后插入一个新的 div。
假设我得到所有段落,例如:
const paragraphs = document.getElementsByTagName("p");
如何循环遍历每个段落,评估它是否符合条件,如果符合则附加一个 div?我意识到对 HTMLCollection 段落的每个元素进行 for 循环不是一个选项,因为 HTMLCollections 是实时的。
假设使用最新版本的 Chrome,使用纯 JavaScript 实现此目的最有效的方法是什么。
最佳答案
不要搞乱实时 HTMLCollections,当需要这些东西时它们是一种倒退。使用 querySelectorAll()
因为它返回的 NodeList 是“静态的”。
详细信息在代码片段中评论
片段
/* Collect all <p> into a NodeList then convert it into an
|| array
*/
var pArray = Array.from(document.querySelectorAll('p'));
/* Using the .map() method
|| on every <p> check to see if each one has any text
|| If so, then replace that text with the index number of
|| the <p>. Otherwise black it out and add a <div> after
|| it with the insertAdjacentHTML() method
*/
pArray.map(function(txt, idx) {
if (txt.textContent.length > 0) {
txt.textContent = idx;
} else {
txt.style.background = 'black';
txt.insertAdjacentHTML('afterend', '<div></div>');
}
});
p {
border: 1px solid red;
font: 10px/1 Arial;
height: 10px;
}
div {
background: red;
height: 10px;
}
<p></p>
<p></p>
<p>TEXT</p>
<p></p>
<p></p>
<p></p>
<p></p>
<p>TEXT</p>
<p></p>
<p>TEXT</p>
<p>TEXT</p>
<p></p>
<p></p>
<p></p>
<p>TEXT</p>
<p></p>
<p>TEXT</p>
<p></p>
<p></p>
<p></p>
<p>TEXT</p>
<p></p>
<p></p>
<p>TEXT</p>
<p>TEXT</p>
关于javascript - 如果满足条件,则尝试在 HTMLCollection 中的项目后面添加元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43361510/