我可以按照这样的顺序选择课程吗?

时间:2017-04-20 14:06:55

标签: javascript html wordpress

所以我在这里用Wordpress生成了这个HTML。我想用JS分别选择DIV。这可能吗?我可以按照JS在HTML中找到它们的顺序来选择它们吗?

我试过这样的事情是可能的(通过添加一个索引号),但我相信它只用于LI元素。但是你明白了。最终结果是使用.className

为每个div对象添加不同的类名

var koffie = document.getElementsByClassName("g-gridstatistic-item-text2")[0];
var brain = document.getElementsByClassName("g-gridstatistic-item-text2")[1];
var tevred = document.getElementsByClassName("g-gridstatistic-item-text2")[2];

console.log(koffie);
console.log(brain);
console.log(tevred);
<div class="g-gridstatistic-wrapper g-gridstatistic-3cols">
    <div class="g-gridstatistic-item">
    <div class="g-gridstatistic-item-wrapper">
    <div class="g-gridstatistic-item-text1 odometer" data-odometer-value="4"></div>
    <div class="g-gridstatistic-item-text2">Kopjes koffie per dag</div>
    </div>
    </div>
    <div class="g-gridstatistic-item">
    <div class="g-gridstatistic-item-wrapper">
    <div class="g-gridstatistic-item-text1 odometer" data-odometer-value="14"></div>
    <div class="g-gridstatistic-item-text2">Brainstormsessies per week</div>
    </div>
    </div>
    <div class="g-gridstatistic-item">
    <div class="g-gridstatistic-item-wrapper">
    <div class="g-gridstatistic-item-text1 odometer" data-odometer-value="12"></div>
    <div class="g-gridstatistic-item-text2">Tevreden klanten</div>
    </div>

4 个答案:

答案 0 :(得分:1)

您的JavaScript代码在检查DOM是否已加载之前正在查找DOM元素。尝试将其包装在事件监听器中,如下所示:

<强> JS

document.addEventListener('DOMContentLoaded', function () {

var koffie = document.getElementsByClassName("g-gridstatistic-item-text2")[0];
var brain = document.getElementsByClassName("g-gridstatistic-item-text2")[1];
var tevred = document.getElementsByClassName("g-gridstatistic-item-text2")[2];

//console.log(koffie);
//console.log(brain);
//console.log(tevred);

/*  to evidence that targeting works:  */
brain.classList.add('addedClass'); 

});

<强> CSS

.addedClass {
  font-size:22px;
  color:red;
}

此处完整演示: https://jsbin.com/saxizeyabo/edit?html,css,js,console,output

答案 1 :(得分:0)

就像这样

var yourVariableName = document.getElementsByClassName("g-gridstatistic-item-text2");

console.log(youVariableName[0]);
console.log(youVariableName[1]);

等像一个数组

答案 2 :(得分:0)

document.querySelectorAll('.g-gridstatistic-item-text2').item(0);

https://developer.mozilla.org/de/docs/Web/API/Document/querySelectorAll

这样,你可以使用CSS-Selectors

答案 3 :(得分:0)

以下代码应该有效。

var classes = document.getElementsByClassName('g-gridstatistic-item-text2');
for(var i=0; i<=classes.length; i++) {
    var appendClass = 'your_class_name'+i;
    classes[i].classList.add(appendClass);
}