Friday , 16 November 2018
Home / Programming / JavaScript / Change HTML Attributes – JavaScript Tutorial
Change HTML Attributes
Change HTML Attributes

Change HTML Attributes – JavaScript Tutorial

This tutorial is part of the JavaScript tutorial series for beginners. To view the whole list of tutorials available and the order in which you should follow them, then click here.

We learned how to change the HTML inside elements. What if we wanted to the change the HTML attributes? This is very easy to do.

First, update the <body> tags inside your HTML document to this.

What we’re going to do is grab the anchor tag’s link and change it with another link.

Now that our HTML document is set up, clear up your script and add this bit of code.

As usual, we’re grabbing any tag with the element ID foo and storing it in a variable. As I stated before, you don’t have to store it in a variable. The reason we do this is to make our code cleaner and to make it easier to explain.

To access a certain attribute, you simply type in the name of the attribute itself. JavaScript treats HTML attributes as properties. You can then change it to whatever value you want.

If you refresh your page, then you should see the link change from Google to my site.

That’s it! While this works, let’s do one more thing before moving on. I want to change the text inside the anchor tag to Jasko Koyn. Add this line of code into your script.

Nothing new here. Just using the innerHTML property to change the text inside the tags.

Conclusion

You can change HTML attributes very easily. You’re allowed to change ANY HTML attribute whether or not it exists.

About Jasko Koyn

Check Also

Audio

Audio – Advanced JavaScript Tutorial

The video and audio objects both have the same events, properties and methods. So, you …

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.