2017-08-10 102 views
1

我有一篇文章,其中包含一堆paragraphs。在第三个paragraph之后,我需要添加一个广告位。之后,每五段添加一个广告位。我试图用这些HTML tags来模仿我想要完成的事情。仅为第三个div添加元素,之后每五个div

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> 
 

 

+2

'(ⅰ%5 == 2)'将返回如果为真i == 2,7,12,17 ... – James

回答

3

获取所有的div元素,然后遍历它们,启动从第二索引循环,然后递增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); 
 
}
<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

这是有道理的,但需要在3和4之间添加元素。 –

+1

您可以使用'insertBefore'在第三个div后添加新元素。更新了解决方案。 –

4

您可以使用nth-child()选择器并设置5n + 3其是从3 DEMO

document.querySelectorAll('div:nth-child(5n + 3)') 
+0

我喜欢你的风格 – Stuart

+0

不错,很干净 –

0

那么每5个元素,简单地令i是基于零的,则加一个偏移量:

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"; 
    } 
    }