Head-First-JavaScript-Programming icon indicating copy to clipboard operation
Head-First-JavaScript-Programming copied to clipboard

Why can't I set an attribute to an element through JS ?

Open adityathebe opened this issue 9 years ago • 2 comments

function init() { var drink = document.getElementById("coffee");
drink.innerHTML = "I love tea."; drink.setAttribute("color", "red"); }

window.onload = init; 

I love coffee.

This is my code. I have selected the element with the id "coffee" and assigned it to the variable "drink". I changed its content with the "innerHTML" property. And, now, I want to set a "color" attribute to the element . What's wrong with my code ? Why is the color not changing ??

adityathebe avatar Jul 23 '15 17:07 adityathebe

Because "color" is not an attribute of an HTML element. "color" is a CSS property. You need to make a CSS class, like this:

.red {
    color: red;
}

and then set the class attribute of your HTML element to the class red:

drink.setAttribute("class", "red");

Hope that helps.

bethrobson avatar Jul 24 '15 03:07 bethrobson

Thanks ! That first line was what I needed.

adityathebe avatar Jul 24 '15 04:07 adityathebe