选择所有h3元素并根据日期模式标记它们

时间:2016-08-12 03:00:33

标签: javascript html getelementbyid

<h3>Thursday, April 7th, 2016 - Wednesday, April 13th, 2016</h3> 
<h3>Thursday, April 14th, 2016 - Wednesday, April 20th, 2016</h3>
<h3>Thursday, April 21st, 2016 - Wednesday, April 27th, 2016</h3>

<script>
var $h3s = $('h3');        
for (var i = 0; i < $h3s.length; i++) {
        var element = $h3s[i];
        var $h3 = $(element);
        var today = 'Thursday, May 14th, 2016';
            $h3.html( $h3.html() + " " + today);

    }
    </script>

有没有办法使用Javascript来选择所有h3元素并根据上述模式标记它们?我知道如何选择和遍历所有h3元素并将它们命名为all,但我想根据这个日期模式命名它们。

2 个答案:

答案 0 :(得分:0)

要选择所有h3元素,您可以使用getElementsByTagName()

var x = document.getElementsByTagName("h3");

然后,您可以使用此变量x来执行任何操作。

根据getElementsByTagName()的{​​{3}}:

  

getElementsByTagName()方法返回所有元素的集合   在具有指定标记名称的文档中,作为NodeList对象。

     

NodeList对象表示节点的集合。节点可以   通过索引号访问。索引从0开始。

答案 1 :(得分:0)

从您尝试过的代码中我想你想要这样的东西......

&#13;
&#13;
var all_h3=document.getElementsByTagName('h3');
var today='Thursday, May 14th, 2016';
for(var i=0;i<all_h3.length;++i){
all_h3[i].innerHTML+=" "+today
}
&#13;
<h3>Thursday, April 7th, 2016 - Wednesday, April 13th, 2016</h3> 
<h3>Thursday, April 14th, 2016 - Wednesday, April 20th, 2016</h3>
<h3>Thursday, April 21st, 2016 - Wednesday, April 27th, 2016</h3>
&#13;
&#13;
&#13;