Friday , 17 November 2017
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

Try-Catch Statement

Try-catch Statement – Advanced JavaScript Tutorial

The try-catch statement is a unique way to handle errors. When errors occur, usually it …

Leave a Reply

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

ULTIMATE WORDPRESS DEVELOPMENT COURSE
Want to learn how to create your own custom WordPress plugins and themes? Check out my course!
Get 93% off my course. You'll also learn how to integrate WooCommerce and BuddyPress into your projects. This is a limited time offer
Yes, I would like to get 93% off your course!
No Thanks!
close-link