var sample = document.getElementById('sample'); function add(cName) { var att = document.createAttribute('class'); // class 속성 Attr 객체 생성 att.value = 'myClass'; sample.setAttributeNode(att); // sample 요소에 att 객체를 세트 } function remove(cName) { try { var att = sample.getAttributeNode('class'); // class 속성을 Attr 객체로 반환 sample.removeAttributeNode(att); // att 객체를 제거 console.log(att); // 출력 } catch (e) { // 제거할 객체가 없다면 예외발생 console.log('제거할 속성이 없습니다.'); } }
<button type="button" onclick="add()">속성 추가</button> <button type="button" onclick="remove()">속성 제거</button> <hr> <p id="sample"> document.createAttribute() 메서드로 새로운 Attr 객체를 생성할 수 있습니다. </p>