Computer >> 컴퓨터 >  >> 프로그램 작성 >> HTML

HTML DOM createAttribute() 메서드

<시간/>

HTML DOM createAttribute() 메서드는 HTML 요소에 대해 JavaScript를 사용하여 특정 속성을 생성하는 데 사용됩니다. createAttribute() 메소드는 주어진 이름으로 속성을 생성하고 속성을 Attr 객체로 반환합니다.

구문

다음은 createAttribute() 메소드의 구문입니다 -

document.createAttribute(attributename)

예시

HTML DOM createAttribute() 메서드의 예를 살펴보겠습니다.

<!DOCTYPE html>
<html>
<head>
<title>CREATE ATTRIBUTE</title>
<style>
   #DIV1{
      margin-top:15px;
      width:250px;
      height:200px;
      border:2px solid blue;
      background-color:lightgreen;
   }
</style>
</head>
<body>
<p>Click the button to create a "class" attribute for the div element</p>
<button onclick="attrCreate()">CREATE</button>
<br>
<div>
<p>This is a sample div</p>
</div>
<script>
   function attrCreate() {
      var x = document.getElementsByTagName("div")[0];
      var att = document.createAttribute("id");
      att.value = "DIV1";
      x.setAttributeNode(att);
   }
</script>
</body>
</html>

출력

이것은 다음과 같은 출력을 생성합니다 -

HTML DOM createAttribute() 메서드

CREATE 버튼 클릭 시 -

HTML DOM createAttribute() 메서드

위의 예에서 -

ID가 "DIV1"인 스타일을 만들었습니다.

#DIV1{
   margin-top:15px;
   width:250px;
   height:200px;
   border:2px solid blue;
   background-color:lightgreen;
}

그런 다음 내부에

요소가 있는

요소를 만들었습니다.

<div>
<p>This is a sample div</p>
</div>

그런 다음 사용자가 클릭할 때 attrCreate() 함수를 실행하는 CREATE 버튼을 만들었습니다. -

<button onclick="attrCreate()">CREATE</button>

attrCreate() 함수는 문서 객체의 getElementsByTagName() 메서드를 사용하여

요소를 가져와 변수 x에 할당합니다. createAttribute() 메서드를 사용하여 "id" 속성을 만들고 value 속성을 사용하여 이전에 만든 스타일의 id인 "DIV1" 값을 할당합니다. 마지막으로 "id" 속성을 값과 함께
요소 −

로 설정합니다.
function attrCreate() {
   var x = document.getElementsByTagName("div")[0];
   var att = document.createAttribute("id");
   att.value = "DIV1";
   x.setAttributeNode(att);
}