The HTML DOM DT object is associated with the HTML <dt> element.Using the DT object we can create the <dt> element dynamically using JavaScript.
Syntax
Following is the syntax for −
Creating a DT object −
var p = document.createElement("DT");
Example
Let us look at an example for the HTML DOM DT object −
<!DOCTYPE html> <html> <body> <h2>DT object example</h2> <p>Create a DT element inside a DL by clicking the below button</p> <button onclick="createDT()">CREATE</button> <script> function createDT() { var Desc = document.createElement("DL"); var DesT = document.createElement("DT"); var tn= document.createTextNode("Mango"); DesT.appendChild(tn); var data = document.createElement("DD"); var tn1 = document.createTextNode("Mango is the king of fruits"); data.appendChild(tn1); document.body.appendChild(Desc); Desc.appendChild(DesT); Desc.appendChild(data); } </script> </body> </html>
Output
This will produce the following output −
On clicking the CREATE button −
In the above example −
We have first created a button CREATE that will execute the createDT() method on being clicked by the user −
<button onclick="createDT()">CREATE</button>
The createDT() method creates a <dl>, <dt> and <dd> element using the createElement() method of the document object and assigns the elements to Desc, DesT and data variables respectively. We then create text node for the <dt> and <dd> element using the createTextNode() method and append them to their respective elements using the appendChild() method.
Finally, we append the <dt> element to <dl> and then <dd> element. The <dl> element is then appended along with the <dt> and <dd> element to the document body using the appendChild() method −
function createDT() { var Desc = document.createElement("DL"); var DesT = document.createElement("DT"); var tn= document.createTextNode("Mango"); DesT.appendChild(tn); var data = document.createElement("DD"); var tn1 = document.createTextNode("Mango is the king of fruits"); data.appendChild(tn1); document.body.appendChild(Desc); Desc.appendChild(DesT); Desc.appendChild(data); }