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

HTML DOM 앵커 type 속성 – 링크의 MIME 타입 설정 및 조회 방법

HTML DOM의 type 속성은 앵커 태그(<a>)와 연결되어 있으며, 링크의 type 속성 값을 설정하거나 가져오는 데 사용됩니다. 이 속성은 HTML5에서 새롭게 도입되었으며, 브라우저에 대한 단순한 참고(제안) 정보로만 활용되기 때문에 반드시 작성해야 하는 필수 속성은 아닙니다. 값으로는 단일 MIME(Multipurpose Internet Mail Extensions) 타입을 가집니다.

문법(Syntax)

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

type 속성 값 반환하기

anchorObject.type

type 속성 값 설정하기

anchorObject.type = MIME-type

예제

앵커 태그의 type 속성을 실제로 다루는 예제를 살펴보겠습니다.

<!DOCTYPE html>
<html>
<body>
<p><a id="Anchor" type="text/html" href="https://www.examplesite.com">example site</a></p>
<p><a id="Anchor2" href="https://www.example.com">example</a></p>
<p>버튼을 클릭하여 type 속성을 설정하고 조회해 보세요.</p>
<button onclick="getType1()">GetType</button>
<button onclick="setType2()">SetType</button>
<p id="Type1"></p>
<script>
    function getType1() {
        var x = document.getElementById("Anchor").type;
        document.getElementById("Type1").innerHTML = x;
    }
    function setType2(){
        document.getElementById("Type1").innerHTML="Type has been set";
        document.getElementById("Anchor2").type="text/html";
    }
</script>
</body>
</html>

실행 결과

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

HTML DOM 앵커 type 속성 – 링크의 MIME 타입 설정 및 조회 방법

GetType 버튼 클릭 시

HTML DOM 앵커 type 속성 – 링크의 MIME 타입 설정 및 조회 방법

SetType 버튼 클릭 시

HTML DOM 앵커 type 속성 – 링크의 MIME 타입 설정 및 조회 방법

예제 설명

위 예제의 동작 방식을 단계별로 살펴보겠습니다.

먼저 각각 id가 AnchorAnchor2인 두 개의 링크를 생성했습니다. Anchor에는 MIME 타입 text/html이 지정되어 있는 반면, Anchor2에는 어떠한 MIME 타입도 지정되어 있지 않습니다.

<p><a id="Anchor" type="text/html" href="https://www.examplesite.com">example site</a></p>
<p><a id="Anchor2" href="https://www.example.com">example</a></p>

다음으로 GetTypeSetType 두 개의 버튼을 만들어, 각각 getType1() 함수와 setType2() 함수가 실행되도록 했습니다.

<button onclick="getType1()">GetType</button>
<button onclick="setType2()">SetType</button>

getType1() 함수는 id가 "Anchor"인 앵커 태그에 지정된 type 값을 읽어 화면에 출력합니다. 반면 setType2() 함수는 id가 "Anchor2"인 앵커 태그의 type을 text/html로 설정합니다.

function getType1() {
    var x = document.getElementById("Anchor").type;
    document.getElementById("Type1").innerHTML = x;
}
function setType2(){
    document.getElementById("Type1").innerHTML="Type has been set";
    document.getElementById("Anchor2").type="text/html";
}

이처럼 HTML DOM의 type 속성을 활용하면 자바스크립트만으로 링크의 MIME 타입을 동적으로 조회하거나 변경할 수 있습니다. 다만 이 속성은 어디까지나 제안(suggestive) 정보일 뿐이며, 브라우저가 이를 강제로 준수하지 않는다는 점을 기억해 두는 것이 좋습니다.