Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
adityathebe opened this issue Jul 23, 2015 · 2 comments
Open

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

adityathebe opened this issue Jul 23, 2015 · 2 comments

Comments

@adityathebe
Copy link

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 ??

@bethrobson
Copy link
Owner

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.

@adityathebe
Copy link
Author

Thanks ! That first line was what I needed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants