使用javascript访问数组项目prop值

时间:2015-10-19 20:01:04

标签: javascript arrays

我有一个div块数组,我正在尝试访问每个“time”标记的innerHTML。如何访问此值?

<div class="review-full-review-single-review-wrap">
    <span class="review-full-timestamp">
        <time itemprop="datePublished" datetime="2015-07-29T11:25:47-07:00">July 29, 2015</time>
    </span>
    <p class="review-camo-rewards">Reward points earned</p>
</div>

<div class="review-full-review-single-review-wrap">
    <span class="review-full-timestamp">
        <time itemprop="datePublished" datetime="2015-07-29T11:25:47-07:00">July 1, 2015</time>
    </span>
    <p class="review-camo-rewards">Reward points earned</p>
</div>

4 个答案:

答案 0 :(得分:1)

你可以这样做:

var elems = document.getElementsByClassName("review-full-review-single-review-wrap")
for (var i = 0; i < elems.length; i++) {
    var timeElems = elems[i].getElementsByTagName("time");
    for (var j = 0; j < timeElems.length; j++) {
        console.log(timeElems[j].innerHTML)
    }
}

演示:http://jsfiddle.net/q311LcL3/

答案 1 :(得分:1)

var blocks = document.querySelectorAll("div time");

for (var i = 0; i < blocks.length; i++) {
    alert(blocks[i].innerHTML);
}

http://jsfiddle.net/f9j6xzm0/

答案 2 :(得分:0)

当您需要使用TagName时,最好的选择是使用getElementsByTagName

var list = document.getElementsByTagName('time');
var dbg = document.getElementById('dbg');
  

dbg.innerHTML = "<hr> result  : <br>"

 for(var i=0 ; i < list.length ; i++ ){
   
   var cur = list[i];
   
   console.log( cur.innerHTML );
   
   dbg.innerHTML += '<br>' + cur.innerHTML;
 }
<div class="review-full-review-single-review-wrap">
    <span class="review-full-timestamp">
        <time itemprop="datePublished" datetime="2015-07-29T11:25:47-07:00">July 29, 2015</time>
    </span>
    <p class="review-camo-rewards">Reward points earned</p>
</div>

<div class="review-full-review-single-review-wrap">
    <span class="review-full-timestamp">
        <time itemprop="datePublished" datetime="2015-07-29T11:25:47-07:00">July 1, 2015</time>
    </span>
    <p class="review-camo-rewards">Reward points earned</p>
</div>

<div id='dbg'></div>

答案 3 :(得分:0)

您也可以使用 forEach

var blocks = document.querySelectorAll(".review-full-timestamp time");
blocks.forEach(function (elem) {
    alert(elem.textContent);
});

关于时间元素的提醒,它尚未得到广泛支持。参考:http://caniuse.com/#search=time