HTML DOM Figcaption object


The HTML DOM Figcaption object is used for representing the HTML5 <figcaption> element. You can create or access a figcaption element using createElement() and getElementById() method respectively.

Syntax

Following is the syntax for −

Creating a Figcaption object −

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

Example

Let us look at an example for the Figcaption object −

Live Demo

<!DOCTYPE html>
<html>
<head>
<script>
   function createCaption() {
      var caption = document.createElement("FIGCAPTION");
      var txt = document.createTextNode("Learn Java Servlets");
      caption.appendChild(txt);
      var f=document.getElementById("Figure1");
      f.appendChild(caption);
   }
</script>
</head>
<body>
<h2>Caption</h2>
<p>Create a caption for the below image by clicking the below button</p>
<button onclick="createCaption()">CREATE</button>
<figure id="Figure1">
<img src="https://www.tutorialspoint.com/servlets/images/servlets-mini-logo.jpg"
alt="Servlets" width="250" height="200">
</figure>
</body>
</html>

Output

This will produce the following output −

On clicking the CREATE button −

In the above example −

We have first created a figure element with id “Figure1” and it contains an img element inside it −

<figure id="Figure1">
<img src="EiffelTower.jpg" alt="Eiffel Tower" width="250" height="200">
</figure>

We then create a button CREATE() that will execute the createCaption() method when clicked by the user −

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

The createCaption() method creates a figcaption element using the createElement() method of the document object. A text node using the createTextNode() method of the document body is created and is appended to the figcaption element. We then get the figure element using the getElementById() method and append the figcaption along with text node as child element using the appendChild() method −

function createCaption() {
   var caption = document.createElement("FIGCAPTION");
   var txt = document.createTextNode("Eiffel Tower in Paris,France");
   caption.appendChild(txt);
   var f=document.getElementById("Figure1");
   f.appendChild(caption);
}

Updated on: 19-Feb-2021

85 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements