HTML DOM Column object


The HTML DOM Column object is associated with the HTML <col> element. The Column object is used to get or set the properties of <col> element. The <col> tag is used only inside a <table> element.

Properties

Following is the property for column object −

PropertyDescription
SpanTo set or return the span attribute value of a column.

Syntax

Following is the syntax for −

Creating a Column object −

var a = document.createElement("COL");

Example

Let us see an example for the column object −

<!DOCTYPE html>
<html>
<head>
<style>
   table, th, td {
      border: 1px solid blue;
   }
   #Col1{
      background-color:pink;
   }
</style>
</head>
<body>
<h3>COL OBJECT</h3>
<table>
<colgroup>
<col id="Col1" span="2">
<col style="background-color:lightgreen">
</colgroup>
<tr>
<th>Fruit</th>
<th>Color</th>
<th>Price</th>
</tr>
<tr>
<td>Mango</td>
<td>Yellow</td>
<td>100Rs</td>
</tr>
<tr>
<td>Guava</td>
<td>Green</td>
<td>50Rs</td>
</tr>
</table>
<p>Click the below button to get span of the "COL1" col element</p>
<button onclick="colObj()">COLUMN</button>
<p id="Sample"></p>
<script>
   function colObj() {
      var x = document.getElementById("Col1").span;
      document.getElementById("Sample").innerHTML = "The Col1 element has span= "+x;
   }
</script>
</body>
</html>

Output

This will produce the following output −

On clicking COLUMN button −

In the above example we have created a table with 2 rows and 3 columns. The table overall has a style applied to it. Inside the table, we have two <col> elements with one having span equals 2 and other has an inline style applied to it. Since for the first <col> span equals 2, its style will apply to exactly two columns and the second <col> will apply its style to the remaining columns −

table, th, td {
   border: 1px solid blue;
}
#Col1{
   background-color:pink;
}
<table>
<colgroup>
<col id="Col1" span="2">
<col style="background-color:lightgreen">
</colgroup>
<tr>
<th>Fruit</th>
<th>Color</th>
<th>Price</th>
</tr>
<tr>
<td>Mango</td>
<td>Yellow</td>
<td>100Rs</td>
</tr>
<tr>
<td>Guava</td>
<td>Green</td>
<td>50Rs</td>
</tr>
</table>

We have then created a button COLUMN that will execute the colObj() method when clicked by the user −

<button onclick="colObj()">COLUMN</button>

The colObj() method gets the first <col> element by using the getElementById() method on document object. It then gets the span attribute value of the <col> element and assigns it to the variable x. The span attribute value that is stored in variable x is then displayed in the paragraph with id “Sample” using the innerHTML property of the paragraph −

function colObj() {
   var x = document.getElementById("Col1").span;
   document.getElementById("Sample").innerHTML = "The Col1 element has span= "+x;
}
raja
Published on 07-Aug-2019 13:56:50
Advertisements