Changing attributes | HTML/JS: Making webpages interactive | Computer Programming | Khan Academy

Changing attributes | HTML/JS: Making webpages interactive | Computer Programming | Khan Academy


I’m back with my webpage about dogs,
and I am very determined to use JavaScript and the DOM api to turn it into a
webpage entirely about cats instead. There is an elephant in the room that I’ve
been ignoring. Well, actually, there’s a dog in the room; two dogs, in fact–
these images. I can’t have images of these adorable dogs on my page about
adorable cats. I need to change them. So, let’s start by finding the images,
using getElementsByTagName. `var imageEls=
document.getElementsByTagName(“img”);` Now, since that returns multiple elements, we need to use a for loop to iterate
through them, so I’ll set that up. `var i=0; itag first. So this CSS query is going to find all
links that have to do with dogs. First I’m going to type `a`,
’cause I’m just looking for links. Then I’m going to say `[href*=”Dog”]`. So this tells CSS to match
any link that has “Dog” in it. And then we’ll set the color to purple.
Ta da, it selected it. So, that’s pretty neat, and this is an
attribute selector, and there’s a lot of neat ways to use attribute selectors to
really dig deep into your document. So now to find that in JavaScript, we can
use document.querySelectorAll, so I’ll say `var linkEls=document.querySelectorAll`,
and then we can just go and paste in the selector that we just made, although
we do have to make sure that we escape our double quotes. There we go.
So now it looks like a good string. And now I need to iterate through these,
so once again we just do our for loop– should be getting really used to
doing these for loops– and for each of them I want to change the link to the
webpage about cats on Wikipedia. So I’m going to say `linkEls[i].href`– because that’s the name of the attribute
that we’re changing– and then equals, then I’ll go find this URL and paste it
down here and just change it to cat, because I’m pretty sure
that’s the URL of that page. Ta da, world catination is complete.
But you are not done learning how to manipulate webpages
with JavaScript, so stick around.

Author: Kevin Mason

1 thought on “Changing attributes | HTML/JS: Making webpages interactive | Computer Programming | Khan Academy

Leave a Reply

Your email address will not be published. Required fields are marked *