What is the DOM title property?
Overview
In this shot, we will learn how to use the DOM property to get or set the title of any element.
The DOM title property provides us a way to get the title when applied to the HTML element. We can also use title to set the title of the HTML element.
When you give a title to an element, you need to assign a value to the
element.titleproperty.
Code
Let’s use the title property on a p tag and give it a title.
Code explanation
-
In line
5, we have aPelement with text to display. -
In line
7, we have a paragraph tag with idelemand atitleattribute. -
In line
9, we write a button tag with achange()function, which will be called when the user clicks on it. -
In line
12, we write the JavaScript code in the script tag. We define achange()function that will be called after a click from the HTML page. -
In line
13, we usedocument.getElementById()and pass idelemin thechange()function to get thepelement and get the element object. -
In line
14, we apply thetitleproperty on the element object we get above and store the return value in a variable. -
In line
15, we print the value returned by thetitleproperty on the console.
Output
When we click the button, the console prints the title we assigned to the p element with id elem.
We have successfully used the title property.