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";
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.
The .style
property modifies the CSS style of an HTML tag. The general syntax is
presented below:
element.style.property = new_style;
.property
must be replaced by CSS property (.color
, .font
, .padding
, .width
, ...) ;new_style
is the value of the new property (red
, 100px
...)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:
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:
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:
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:
Which property allows you to change the text of a tag?
.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?
.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">
element.attribute.src = "happy.jpg";
element.setAttribute ('src', 'happy.jpg');
element.setAttribute ('happy.jpg', 'src');
src
attribute of the img
tag.
Try again...