我有一篇文章,其中包含一堆paragraphs
。在第三个paragraph
之后,我需要添加一个广告位。之后,每五个段落添加另一个广告位。我尝试使用这些HTML tags
来模仿我想要完成的任务。
for(var i = 0; i<tasks.length; i++){
if(tasks[i].tagName == 'DIV'){
if (i && (i % 5 == 0)) {
//Logic to add elements go here
}
}
}
<div>1</div>
<div>2</div>
<div>3(Here is where the element will be added)</div>
<div>4</div>
<div>5</div>
<div>6</div>
<div>7</div>
<div>8(Here is where the element will be added)</div>
答案 0 :(得分:4)
您可以使用nth-child()
选择器并设置5n + 3
,这是3 DEMO
document.querySelectorAll('div:nth-child(5n + 3)')
答案 1 :(得分:3)
获取所有div元素,然后遍历它们,从第二个索引开始for循环,然后以5的步长递增
}
var div = document.getElementsByTagName('div');
for(var i = 2; i<div.length; i += 5){
let para = document.createElement("P");
let t = document.createTextNode("new content");
para.appendChild(t);
//div[i].after(para); this is experimental feature, might not be supported in all the browsers
div[i].parentNode.insertBefore(para, div[i].nextSibling);
}
答案 2 :(得分:0)
好吧,简单地让我基于零,然后添加一个偏移量:
var tasks = document.body.children;
var off = 2;
for(var i = 0; i < tasks.length - off; i++){
if(tasks[i+off].tagName == 'DIV'){
if ( !(i % 5)) {
tasks[i+off].innerHTML += "sth";
}
}