getElementsByClassName() method in JavaScript - example 2
by danielkwood
HTML
<html>
<head>
<title>getElementsByClassName() method</title>
<script src="script.js"></script>
</head>
<body>
<p class="mytext">Click the button</p>
<p class="mytext">Click the button</p>
<p class="mytext">Click the button</p>
<p class="mytext">Click the button</p>
<button onclick="changeText();">Click me!</button>
</body>
</html>
JavaScript
function changeText(){
var mytext = document.getElementsByClassName('mytext');
// This will change the innerHTML and colour of all paragraph elements that belong to the class 'mytext'
for(var i = 0; i < mytext.length; i++){
mytext[i].innerHTML = "You clicked the button!";
mytext[i].style.color = "green";
}
}