Reputation: 269
I want to change the color of more than one element in a page by clicking on a button. I really thought this would be very but I am having lots of difficulty achieving it. My code as follows changes the first element - and I know this is because i am using document.getElementById but when i change it to document.getElementByClass, it stops working at all. I have tried inline styles and internal styles to no avail. Can someone please please please explain how to do this. I doubt this is impossible. Thanks.
<html>
<head>
<style>
#p1{color:#4d982b;}
</style>
<script type="text/javascript">
function ChangeStyle()
{
document.getElementByClass("p1").style.color="#aaaaaa";
}
</script>
</head>
<body>
<p class="p1">Hello world!</p>
<p class="p1">Hello world!</p>
<input type="button" onclick="ChangeStyle()" value="Change style" />
</body>
Upvotes: 0
Views: 6532
Reputation: 114347
IDs must be unique, so use class names instead:
<p class="p1">Hello world!</p>
<p class="p1">Hello world!</p>
document.getElementsByClassName
results in an array. You must loop through each element:
var list = document.getElementsByClassName("p1");
for (var i = 0; i < list.length; i++) {
list[i].style.color="#aaaaaa";
}
Upvotes: 0
Reputation: 91
Getelementbyid method only works with one element. Try getelementsbyid which returns an array.
Upvotes: 0
Reputation: 6715
I believe you're thinking of document.getElementsByClassName - maybe someone can clarify for me but I believe getElementById is the only singular return on getting elements.
So lets say you're trying to get all elements with the class "foo"...
var elem = document.getElementsByClassName('foo')
for (var i = 0;i < elem.length; i++)
{
elem[i].style.color = '#aaaaaa'
}
There's probably syntax errors up there but I think you get the general idea~
Upvotes: 0
Reputation: 20993
You can't have elements on the page with the same id
. id
is meant to be unique to a single element so when you call getElementById("p1")
it will only select the first id
with value of "p1"
.
The solution is to use classes, or have 2 getElementById
calls, with 2 different id
's.
Upvotes: 1
Reputation: 51435
this is typically done using a class rather than an id.
There can be only one id per page. change your code to
<p class="myclass">Hello world!</p>
<p class="myclass">Hello world!</p>
Then use javascript to alter the class color attributes
Here is a link which will help How to getElementByClass instead of GetElementById with Javascript?
Upvotes: 2