So now that we've seen how you can manipulate the style and the text of an HTML element, the last thing
I want to show you is how to manipulate, are the attributes of any element.
So just a reminder, the attributes are all the things that get colored in orange in Atom,
so for example, class is an attribute, or the href for an anchor tag is the attribute, or the src for
an image. They’re all attributes. Everything that goes inside the tag, other than the tag name itself, are attributes.
So we have a link up here that points towards Google,
right?
It takes us to the Google search page.
Now, what if we've gone crazy and we decided to point people towards Bing instead?
Well, we can get a list of attributes that are attached to the element by saying document.querySelector
(“a”), and that of course gets us our first anchor tag which points towards Google.
And now if we say .attributes, then that will give us a list of all the attributes that are currently
attached to this HTML element.
And as you can see there's only one and that is the href.
So we can now retrieve the current value of that attribute by saying .getAttribute,
and notice how this is singular and not plural,
so we're only getting back the value of a single attribute, and we have to specify the name of the attribute
that we want.
So in this case it's the href, and you can see that we get back that currently it's pointing towards
google.com.
So now if we wanted to change this then instead of saying getAttribute, we can say setAttribute, but
this method takes two parameters, two inputs essentially.
One is which attribute do you want to change,
and the second one after the comma is what do you want to change it to?
And we're going to say www.bing.com.
Wow, I've never typed that in my life before.
All right. So now if I click on this link, even though it still says Google because the innerHTML is "Google",
if I click on it, you can see it takes me to this wonderful web site that nobody has ever used in their
lives before.
All right. Cool.
So this is a really quick and easy way of getting, setting, and seeing what the attributes are for any
element you select in the DOM.