HTML DOM Column span Property


The HTML DOM Column span property is associated with the colspan attribute inside the <td> element in the HTML. Using the colSpan property we can set or return the colspan attribute of a table. The colspan attribute is used to create the no. of columns that a table should span to.

Syntax

Following is the syntax for −

tabledataObject.colSpan = number

Here, number represents the number of columns the table should span to.

Example

Let us see an example for the colSpan property −

Live Demo

<!DOCTYPE html>
<html>
<head>
<style>
table, th, td {
   border: 1px solid blue;
}
</style>
</head>
<body>
<h2>Monthly Savings</h2>
<table>
<tr>
<th>Month</th>
<th>Savings</th>
</tr>
<tr>
<td class="TD1" colspan="2">January</td>
<td>$100</td>
</tr>
<tr>
<td class="TD1" colspan="2">February</td>
<td>$100</td>
</tr>
</table>
<br>
<button onclick="changeSpan()">CHANGE</button>
<script>
   var x=document.getElementsByClassName("TD1").length;
   function changeSpan() {
      for(var i=0;i<=x;i++){
         document.getElementsByClassName("TD1")[i].colSpan = "1";
      }
   }
</script>
</body>
</html>

Output

This will produce the following output −

On clicking CHANGE −

In the above example −

We have taken a table where the first elements beginning from second row i.e. January and February are having colspan equals 2. This makes the table having three rows and three columns. The table has a style applied to it to make it look different from others −

table, th, td {
   border: 1px solid blue;
}
<table>
<tr>
<th>Month</th>
<th>Savings</th>
</tr>
<tr>
<td class="TD1" colspan="2">January</td>
<td>$100</td>
</tr>
<tr>
<td class="TD1" colspan="2">February</td>
<td>$100</td>
</tr>
</table>

We have then created the CHANGE button that will execute changeSpan() method when clicked upon by the user −

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

The changeSpan() method gets both the <div> elements using getElementsByClassName() method on the document object and using indexing to access both of them. It then gets the colSpan attribute value of both the <div> elements and changes them from 2 to 1 −

var x=document.getElementsByClassName("TD1").length;
function changeSpan() {
   for(var i=0;i<=x;i++){
      document.getElementsByClassName("TD1")[i].colSpan = "1";
   }
}

Updated on: 20-Feb-2021

125 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements