HTML DOM의 Column 객체는 HTML <col> 요소와 연관된 객체입니다. 이 객체를 사용하면 <col> 요소의 속성을 가져오거나 설정할 수 있습니다. 참고로 <col> 태그는 반드시 <table> 요소 내부에서만 사용해야 합니다.
Column 객체의 속성
Column 객체가 제공하는 속성은 다음과 같습니다.
| 속성 | 설명 |
|---|---|
| span | 해당 열(column)의 span 속성 값을 설정하거나 반환합니다. |
문법
Column 객체를 생성하는 문법은 다음과 같습니다.
var a = document.createElement("COL");예제
이제 Column 객체를 활용한 실제 예제를 살펴보겠습니다.
<!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>아래 버튼을 클릭하면 "COL1" col 요소의 span 값을 확인할 수 있습니다.</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>실행 결과
위 코드를 실행하면 다음과 같은 화면이 출력됩니다.

COLUMN 버튼을 클릭한 후의 결과는 다음과 같습니다.

코드 상세 분석
위 예제에서는 2개의 행과 3개의 열로 구성된 테이블을 생성했습니다. 테이블 전체에는 기본 스타일이 적용되어 있으며, 테이블 내부에는 두 개의 <col> 요소가 포함되어 있습니다. 첫 번째 <col>은 span 값이 2로 지정되어 있고, 두 번째 <col>에는 인라인 스타일이 적용되어 있습니다.
첫 번째 <col>의 span 값이 2이므로 해당 스타일(분홍색 배경)은 정확히 두 개의 열에 적용되며, 두 번째 <col>의 스타일(연두색 배경)은 나머지 열에 적용됩니다.
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>다음으로 COLUMN 버튼을 생성했으며, 사용자가 이 버튼을 클릭하면 colObj() 메서드가 실행됩니다.
<button onclick="colObj()">COLUMN</button>
colObj() 메서드는 document 객체의 getElementById() 메서드를 사용하여 첫 번째 <col> 요소에 접근합니다. 그런 다음 해당 <col> 요소의 span 속성 값을 가져와 변수 x에 할당합니다. 마지막으로 변수 x에 저장된 span 속성 값은 innerHTML 속성을 통해 id가 "Sample"인 단락(paragraph)에 표시됩니다.
function colObj() {
var x = document.getElementById("Col1").span;
document.getElementById("Sample").innerHTML = "The Col1 element has span= "+x;
}