As I mentioned in my comment, it is invalid to have multiple elements with the same id
. The purpose of an id
is to uniquely identify an element, so having more than one with the same id
defeats that purpose.
Next, .getElementById()
(notice it's not called .getElementsById()
) only returns a reference to the first matching element it finds, so after finding the first one, it stops and that's why only the first h1
is changing its color.
If you want to group together elements that are somehow related, you can give them all the same class
. Then, you can locate all the class members with .querySelectorAll()
. This will return a collection, which you can then loop over and work with each element within the collection as you wish.
Also, avoid inline styles whenever you can. As you saw with your original code, you had to repeat the same styling instructions 3 times because you wanted the same style in 3 places. Instead, create a pre-defined CSS class that each of the elements can just use.
Here all that is put together.
<!DOCTYPE html>
<html>
<head>
<title>Styling with JavaScript</title>
<style>
/* Use pre-defined CSS classes whenever possible
instead of inline styles in your HTML */
.heading { color: #ffff00; font-size: 20px; }
.newColor { color:#00f; }
</style>
</head>
<body>
<!-- See how clean the HTML is now? -->
<h1 class="heading">Hello1</h1>
<h1 class="heading">Hello2</h1>
<h1 class="heading">Hello3</h1>
<script>
// Get all the elements that match the CSS selector
// passed into .querySelectorAll() into a collection
// and loop over the collection
document.querySelectorAll(".heading").forEach(function(element){
// Override the original color by adding an additional class
element.classList.add("newColor");
});
</script>
</body>
</html>