JavaScript — Getting & Settings Attributes
In the last article I covered how to chnage the inner text and inner html of an element or elements. In this article I’ll cover getting and setting attributes of those elements.
Here I have an a take with an href attribute and a p tag with a class attribute. There are several attributes we can either get or set in JavaScript. Lets get the href attribute from that a tag.
Here I’ve stored a reference to the a tag in a const called link
. Then I’m logging link.getAttribute()
. I’ve fed the method a string href
. When I check out the console in the browser it outputs that value.
Lets try to set it now.
Instead of the link taking us to Google I told it to take us to Yahoo. When I inspect this element in the browser, you’ll see that the value has changed.
Another example:
Here I’m grabbing the p tag and changing its attribute to success. If I inspect this in the elements, you’ll see the attribute has changed.
This could be a useful implemention for displaying whether something worked or not. If not, its an error which we could then change the color to red or if so, we could change the color of the message to green.
Now lets set an attribute to an html element that doesnt already exist. I’m going to add a style attribute to the p tag through JavaScript.
Here Im just adding a style attribute and setting the color of the text to green.
Heres a practical example:
Here I’ve got a bool that just checks whether you won or lost. When I set it to true, the text changes to green and says You Win! When I change it to false the text changes to red and says You Lose!
In later article, I’ll cover how we can dynamically change things at runtime.