Understanding how you can perform DOM manipulation using JavaScript with options like JavaScript innerHTML allows you to add handy features to your website.
In this tutorial, you will learn how you can change HTML using JavaScript, and read about the most popular ways of adjusting HTML content through the use of JavaScript. That includes JavaScript innerHTML property, which allows you to change the content of any text tag according to your needs.
Contents
JavaScript innerHTML: Main Tips
- To allow JavaScript to change the content of an HTML element, we use HTML DOM.
- JavaScript can be used to create HTML content that is dynamic.
Changing HTML
In JavaScript, document.write()
is the first DOM manipulation function. It's only logical we start our tutorial with it, right? Using this command, you can write directly to the HTML output stream.
This JavaScript write HTML method is commonly applied for testing. When using it for different purposes, a warning should be taken into account: you should always execute document.write()
when the document is already loaded - otherwise, an overwrite will occur.
- Easy to use with a learn-by-doing approach
- Offers quality content
- Gamified in-browser coding experience
- The price matches the quality
- Suitable for learners ranging from beginner to advanced
- Free certificates of completion
- Focused on data science skills
- Flexible learning timetable
- Simplistic design (no unnecessary information)
- High-quality courses (even the free ones)
- Variety of features
- Nanodegree programs
- Suitable for enterprises
- Paid Certificates of completion
- A wide range of learning programs
- University-level courses
- Easy to navigate
- Verified certificates
- Free learning track available
- University-level courses
- Suitable for enterprises
- Verified certificates of completion
Using innerHTML to Modify Content
The easiest way of editing content in an HTML element is to use the innerHTML
property.
In the code example below, we're using the JavaScript innerHTML
property to change the content of the element <p>
:
document.getElementById("p2").innerHTML = "Hello World again!";
Now, in the code example below, we change the content of the element <h1>
:
var element = document.getElementById("id1");
element.innerHTML = "New heading";
Altering Attribute Value
You can also change the values of HTML attributes.
Take a look at the example below. In it, we change the value of the src
attribute for the <img>
element:
JavaScript innerHTML: Summary
- You can use JavaScript innerHTML property to change the content in the HTML.
- You can learn more about JavaScript innerHTML in this tutorial.
- You can use JavaScript to change the values of HTML element's attributes as well.