HTML DOM ColumnGroup span Property


The HTML DOM ColumnGroup span property is associated with the span attribute of the HTML <colgroup> element. The ColumnGroup span property set or returns the value of the span attribute of a column group. The span attribute is used to define the number of columns a <colgroup> element should span to.

Syntax

Following is the syntax for −

Setting the ColumnGroup span property −

columngroupObject.span = number

Here, the number specifies the number of columns the <colgroup> element should span to.

Example

Let us look at an example for the ColumnGroup span property −

<!DOCTYPE html>
<html>
<head>
<style>
   table, th, td {
      border: 1px solid blue;
   }
</style>
</head>
<body>
<table>
<colgroup id="Colgroup1"></colgroup>
<tr>
<th>Fruit</th>
<th>COLOR</th>
<th>Price</th>
</tr>
<tr>
<td>watermelon</td>
<td>dark green</td>
<td>40Rs</td>
</tr>
<tr>
<td>papaya</td>
<td>yellow</td>
<td>30Rs</td>
</tr>
</table>
<p>lick the button to change the background color of the first two columns.
<button onclick="changeColor()">CHANGE</button>
<script>
   function changeColor() {
      document.getElementById("Colgroup1").span = "2";
      document.getElementById("Colgroup1").style.backgroundColor = "lightgreen";
   }
</script>
</body>
</html>

Output

This will produce the following output −

On clicking the CHANGE button −

In the above example −

We have created a table with two rows and three columns.There is also some styling applied to the table, th and td elements −

table, th, td {
   border: 1px solid blue;
}
<table>
<colgroup id="Colgroup1"></colgroup>
<tr>
<th>Fruit</th>
<th>COLOR</th>
<th>Price</th>
</tr>
<tr>
<td>watermelon</td>
<td>dark green</td>
<td>40Rs</td>
</tr>
<tr>
<td>papaya</td>
<td>yellow</td>
<td>30Rs</td>
</tr>
</table>

We have then created a button CHANGE that will execute changeColor() method when clicked upon by the user.

<button onclick="changeColor()">CHANGE</button>

The changeColor() function gets the <colgroup> element using the getElementById() method and giving the <colgroup> element id as parameter. It then sets the <colgroup> element span to 2 and changes its background color to green. This makes the first two columns from left green as specified by the span attribute of the <colgroup> element:

function changeColor() {
   document.getElementById("Colgroup1").span = "2";
   document.getElementById("Colgroup1").style.backgroundColor = "lightgreen";
}

Updated on: 07-Aug-2019

57 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements