Lesson 3.8. Changing HTML

.innerText

So far, we have mostly used the innerHTML property which modify the content of an HTML tag. There are other properties that allow to modify other properties of HTML elements:

let element = getElementById ('MyID');
element.innerText = "New Content";

.innerHTML

With innerText you can only insert text. If you want to insert HTML, you must use the innerHTML property:

element.innerHTML = '<img src="image.jpg">';

The above example add an image in the HTML tag.

.style

The .style property modifies the CSS style of an HTML tag. The general syntax is presented below:

element.style.property = new_style;

Here are some examples:

element.style.color = 'red';
element.style.fontWeight = 'bold';
element.style.backgroundColor = '#FF00FF';
element.style.paddingTop  = '100px';

The baove example changes the sytle of a paragrph:

setAttribute

The setAttribute() function is used to modify the attribute of an HTML tag. The general syntax is given by :

element.setAttribute(name, value)

Here are some examples:

element.setAttribute('src',  "image.png";
element.setAttribute('href', "https://www.google.com";
element.setAttribute('style', "color:red;";

The above example changes the src attribute of an image:

Exercises

Exercise 1

Modify the code below so that the text takes the color of the clicked button:

<p id="text">Click to change my color.</p>

<button>Red</button>
<button>Green</button>
<button>Blue</button>
<button>Black</button>

Here is the expected result:

Exercise 2

Modify the code below so that the link is modified when the user clicks on it. The new link will be https://lucidar.me/fr/:

<a href="https://www.google.com" target="_blank">Google</a>

Note that this type of link is to be avoided. Here is the expected result:

Quiz

Which property allows you to change the text of a tag?

Check Bravo ! Who can do more can do less: .innerHtml also allows you to edit the content, even if there is no HTML inside. Try again...

What syntax allows you to modify the style of an HTML tag?

Check Bravo ! By writing .setAttribute('style', 'colo:red') we can also change the CSS style. Try again...

Which syntax allows you to modify the following image:

<img src="sad.jpg">
Check Bravo ! Here we want to change the src attribute of the img tag. Try again...

See also


Last update : 10/10/2022