HTML DOM dl object


The HTML DOM dl object is associated with the HTML <dl> element. The <dl> element is for creating the description list. Using the dl object we can dynamically create and acess the <dl> element using JavaScript.

Syntax

Following is the syntax for −

Creating a description list −

var p = document.createElement("DL");

Example

Let us look at an example for the dl object −

<!DOCTYPE html>
<html>
<body>
<h2>Div object example</h2>
<p>Create a div by clicking the below button</p>
<button onclick="createDiv()">CREATE</button>
<script>
   function createDiv() {
      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 createDiv() method on being clicked by the user −

<button onclick="createDiv()">CREATE</button>

The createDiv() method creates a <dl>, <dt> and <dd> element using the createElement() method of the document object and assings 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 createDiv() {
   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);
}
raja
Published on 08-Aug-2019 14:02:53
Advertisements