Javascript DOM - 如何循環(huán)遍歷從getElementsByClassName返回的所有元素
我們想知道如何循環(huán)遍歷從getElementsByClassName返回的所有元素。
<!DOCTYPE html>
<html>
<head>
<style type='text/css'>
.first, .second {
border: 1px solid black;
width: 200px;
}
</style>
<script type='text/javascript'>
window.onload=function(){
var elements = document.getElementsByClassName('first');
Array.prototype.forEach.call(elements, function (element) {
element.innerHTML = 'Your text goes here';
});
}
</script>
</head>
<body>
<div class='first'>First</div>
<div class='first'>First too</div>
<div class='second'>Second</div>
</body>
</html>
The code above is rendered as follows: