HTML DOM getAttribute() 메서드는 특정 HTML 요소와 관련된 속성을 가져오거나 설정하는 데 사용됩니다. 요소에 지정된 속성이 포함되어 있지 않으면 null 또는 빈 문자열을 반환합니다.
구문
다음은 getAttribute() 메소드의 구문입니다 -
element.getAttribute(attributename)
여기에서 attributename은 문자열 유형이며 필수 매개변수입니다. 값을 얻으려는 속성 이름을 나타냅니다.
예시
getAttribute() 메소드의 예를 살펴보겠습니다 -
<!DOCTYPE html>
<html>
<head>
<script>
function getAttr() {
var a = document.getElementsByTagName("a")[0].getAttribute("href");
document.getElementById("Sample").innerHTML = a;
}
</script>
</head>
<body>
<h1>getAttribute() example</h1>
<a href="https://www.google.com">GOOGLE</a>
<p>Get the href attribute value of the above link by clicking the below button</p>
<button onclick="getAttr()">GET</button>
<p id="Sample"></p>
</body>
</html> 출력
이것은 다음과 같은 출력을 생성합니다 -

GET 버튼 클릭 시 -

위의 예에서 -
href 속성 값이 https://www.google.com −
으로 설정된 앵커 요소를 먼저 만들었습니다.<a href="https://www.google.com">GOOGLE</a>
그런 다음 사용자가 클릭할 때 getAttr() 메서드를 실행할 버튼 GET을 만들었습니다.
<button onclick="getAttr()">GET</button>
getAttr() 메서드는 문서 객체의 getElementByTagName() 속성을 사용하여 HTML 문서의 첫 번째 요소를 가져옵니다.
그런 다음 getAttribute() 메서드를 사용하여 href 속성 값을 가져오고 해당 값을 변수 a에 할당합니다. 이 값은 innerHTML 속성을 사용하여 id가 "Sample"인 단락에 표시됩니다 -
function getAttr() {
var a = document.getElementsByTagName("a")[0].getAttribute("href");
document.getElementById("Sample").innerHTML = a;
}