0

I want to change an attribute using this:

document.getElementsByClassName('a').setAttribute("color","red")

but this does not work in Chrome. The console told me

setAttribute is not a function

Can you please tell me what javascript function to use? Thank you.

Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112
John Hao
  • 39
  • 7
  • This will help you to find out the answer to your query. [Changing background color of all elements with the same class](https://stackoverflow.com/questions/14307163/changing-background-color-of-all-elements-with-the-same-class) – Ravat Tailor Sep 28 '17 at 04:01

2 Answers2

1

document.getElementsByClassName returns an array-like object not a single element. You need to access the indexed item. Also set attibute style instead of color. If you have more than one element, you can use loop to iterate over the array-like object and set the attributes.

document.getElementsByClassName('a')[0].setAttribute("style","color:red")
------------------------------------^^^----------------------------

Code example

document.getElementsByClassName('a')[0].setAttribute("style","color: red");
<p class='a'>Test 1</p>
<p>Test 2</p>

With many elements

Array.prototype.forEach.call(document.getElementsByClassName('a'), 
                             item => item.setAttribute("style","color: red"));
<p class='a'>Test 1</p>
<p class='a'>Test 2</p>
<p>Test 3</p>
Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112
0

Check this out.

you can try like this document.getElementsByClassName('.a').style.color = "red";

I think this is you want.

Mhd
  • 771
  • 1
  • 8
  • 15