Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Very Basic setAttribute on JavaScript

I'm very beginner in JavaScript and I can't understand why in this simple code, appears in the console color.setAttribute is not a function

<style>
	.red {color:red;}
	.blue { color: blue;}
</style>
</head>
<body>
<p class="red">Hello World</p>
<script>
	var color = document.getElementsByClassName("red");
	color.setAttribute("class","blue");
</script>
To my knowledge when declare the variable color, I create an element object and I can use the method : setAttribute.

Thanks in advance, and sorry if my question is to silly.

like image 357
Rebecca Sanders Avatar asked May 10 '26 07:05

Rebecca Sanders


1 Answers

document.getElementsByClassName("red") returns a dom object which is array like object. so you should write the following.

var color=document.getElementsByClassName("red")[0];
color.setAttribute("class","blue");
like image 179
Akhilesh Kumar Avatar answered May 12 '26 22:05

Akhilesh Kumar