Click here to Skip to main content
15,885,216 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I need to write a loop which adds 10 div elements and sets the contents to the count value ( 1, 2, 3, …). Set the color of the first five elements are red and the last five elements are green using these methods : attr(), property() and style()

My attempt does not show colors and I have not used attr()

What I have tried:

<script src='https://d3js.org/d3.v7.min.js'></script>
<style>
	.demo {
		color: 'red'
	}
</style>

<div id="demo">
<script>
	let text = "";
for (let i = 1; i < 5; i++) {
  text += i + "<br>";
}
document.getElementById("demo").innerHTML = text;

</div>

<div id="demo2">
	<script>
		let text2 = "";
for (let i = 5; i <=10 ; i++) {
  text2 += i + "<br>";
}
document.getElementById("demo2").innerHTML = text2;
	</script>
</div>


<script>
	d3.selectAll(".demo2").style('color','green');
</script>
Posted
Updated 16-Jan-22 7:54am

1 solution

Use the following code:

<script src='https://d3js.org/d3.v7.min.js'></script>
<style>
	.redColor {
		color: 'red'
	}
	.greenColor {
		color: 'green'
	}
</style>

<div id="demo">
<script>
	let text = "";
	for (let i = 1; i <= 10; i++) {		
		if(i<=5)
		{
			text += i + "<br>";
			document.getElementsByTagName("TagName")[0].setAttribute("class", "redColor");
		}	
		else
		{
			text2 += i + "<br>";
			document.getElementsByTagName("TagName")[0].setAttribute("class", "greenColor");
		}	
	}
</script>
</div>
 
Share this answer
 
v2
Comments
123usersomeone 16-Jan-22 15:13pm    
Hi, it gives me this error -
Uncaught TypeError: Cannot read properties of undefined (reading 'setAttribute')
What can I do? Thanks

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900