i just wanna ask how to change or display the different color with “getElementsByClassName() Method” in javascript,so here i want to change the bacground color blue from class “ex”,and color red form class “example”,but it doesnt work.
JavaScript
x
47
47
1
<!DOCTYPE html>
2
<html>
3
<head>
4
<style>
5
.example {
6
border: 1px solid black;
7
padding 8px;
8
}
9
</style>
10
</head>
11
<body>
12
13
<h1>The Document Object</h1>
14
<h2>The getElementsByClassName() Method</h2>
15
16
<p>Change the background color of all elements with class="example":</p>
17
18
<div class="example">
19
A div with class="example"
20
</div>
21
<br>
22
<div class="ex">
23
A div with class="example"
24
</div>
25
26
<p class="example">
27
A p element with class="example".
28
</p>
29
<p class="ex">
30
A p element with class="example".
31
</p>
32
33
<p>A <span class="example">span</span> element with class="example".</p>
34
35
<script>
36
const collection = document.getElementsByClassName("example");
37
for (let i = 0; i < collection.length; i++) {
38
collection[i].style.backgroundColor = "red";
39
}
40
const collection = document.getElementsByClassName("ex");
41
for (let i = 0; i < collection.length; i++) {
42
collection[i].style.backgroundColor = "blue";
43
}
44
</script>
45
46
</body>
47
</html>
Advertisement
Answer
your code works fine but you had two variables with the name collection
rename one of them
JavaScript
1
50
50
1
<!DOCTYPE html>
2
<html>
3
4
<head>
5
<style>
6
.example {
7
border: 1px solid black;
8
padding 8px;
9
}
10
</style>
11
</head>
12
13
<body>
14
15
<h1>The Document Object</h1>
16
<h2>The getElementsByClassName() Method</h2>
17
18
<p>Change the background color of all elements with class="example":</p>
19
20
<div class="example">
21
A div with class="example"
22
</div>
23
<br>
24
<div class="ex">
25
A div with class="example"
26
</div>
27
28
<p class="example">
29
A p element with class="example".
30
</p>
31
<p class="ex">
32
A p element with class="example".
33
</p>
34
35
<p>A <span class="example">span</span> element with class="example".</p>
36
37
<script>
38
const collection = document.getElementsByClassName("example");
39
for (let i = 0; i < collection.length; i++) {
40
collection[i].style.backgroundColor = "red";
41
}
42
const collection2 = document.getElementsByClassName("ex");
43
for (let i = 0; i < collection2.length; i++) {
44
collection2[i].style.backgroundColor = "blue";
45
}
46
</script>
47
48
</body>
49
50
</html>