Computer >> 컴퓨터 >  >> 프로그래밍 >> HTML

HTML DOM ColumnGroup span 속성 완벽 가이드 – 문법과 실전 예제

HTML DOM의 ColumnGroup span 속성은 HTML <colgroup> 요소의 span 속성과 연결된 기능입니다. 이 속성을 활용하면 열 그룹(column group)의 span 속성 값을 설정하거나 현재 값을 반환할 수 있습니다. 여기서 span 속성은 <colgroup> 요소가 몇 개의 열에 걸쳐 적용될지를 정의하는 역할을 합니다.

문법(Syntax)

ColumnGroup span 속성의 기본 문법은 다음과 같습니다.

span 속성 설정하기:

columngroupObject.span = number

여기서 number는 <colgroup> 요소가 적용될 열의 개수를 지정합니다.

예제(Example)

ColumnGroup span 속성의 실제 동작 방식을 예제를 통해 확인해 보겠습니다.

<!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)

위 코드를 실행하면 다음과 같은 화면이 출력됩니다.

HTML DOM ColumnGroup span 속성 완벽 가이드 – 문법과 실전 예제

CHANGE 버튼을 클릭한 후의 결과입니다.

HTML DOM ColumnGroup span 속성 완벽 가이드 – 문법과 실전 예제

예제 상세 분석

위 예제에서 어떤 작업이 이루어졌는지 단계별로 살펴보겠습니다.

먼저 두 개의 행과 세 개의 열로 구성된 테이블을 생성하고, table, th, td 요소에 다음과 같은 스타일을 적용했습니다.

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>

다음으로, 사용자가 클릭하면 changeColor() 메서드를 실행하는 CHANGE 버튼을 만들었습니다.

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

changeColor() 함수는 getElementById() 메서드에 <colgroup> 요소의 id를 매개변수로 전달하여 해당 요소를 가져옵니다. 그런 다음 <colgroup> 요소의 span 값을 2로 설정하고 배경색을 연두색(lightgreen)으로 변경합니다. 이 과정에서 span 속성에 지정된 값에 따라 왼쪽에서 첫 번째와 두 번째 열이 초록색으로 표시됩니다.

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