选择其他div中的每个第二个div

时间:2017-08-10 01:56:29

标签: javascript css

<div id="random numbers">
<div class="column-1"><a href="..."></a></div>
<div class="column-1"><a href="...">this value I want to change</a></div>
<div class="column-1"><a href="..."></a></div>
</div>

从早期的建议,我有这个代码:

var elements = document.querySelectorAll('.column-1 a');
for (var i = 0; i < elements.length; i++) {
  elements[i].outerHTML = "OVERRIDDEN";
  }

我遇到的问题是,这会替换每个div <a内的每个<div id="random numbers">,而我希望它只替换每个随机数div中的第二列-1。

提前谢谢你!

2 个答案:

答案 0 :(得分:0)

document.querySelectorAll(&#39; .column-1 a&#39;)[1] .outerHTML =&#34; OVERRIDDEN&#34;;

答案 1 :(得分:0)

只需使用i

即可
var elements = document.querySelectorAll('.column-1');
for (var i = 0; i < elements.length; i++) {
  if(i%2) { // override 2nd, 4th, etc.
    elements[i].outerHTML = "OVERRIDDEN";
  }
}

https://jsfiddle.net/ishukshin/av6t6kxz/