속성 API
속성을 제어하는 API
Element.getAttribute(name);
Element.setAttribute(name, value);
Element.hasAttribute(name);
Element.removeAttribute(name);
<a id="target" href="http://opentutorials.org">opentutorials</a>
<script>
let t = document.getElementById('target');
console.log(t.getAttribute('href')); // http://opentutorials.org
t.setAttribute('title', 'opentutorials.org'); // title 속성의 값을 설정한다.
console.log(t.hasAttribute('title')); // true, title 속성의 존재여부를 확인한다.
t.removeAttribute('title'); // title 속성을 제거한다.
console.log(t.hasAttribute('title')); // false, title 속성의 존재여부를 확인한다.
</script>
속성과 프로퍼티
<p id="target">
Hello world
</p>
<script>
let target = document.getElementById('target');
// attribute 방식
target.setAttribute('class', 'important');
// property 방식
target.className = 'important';
</script>
attribute 방식
property 방식
class
className
readonly
readOnly
rowspan
rowSpan
colspan
colSpan
usemap
userMap
frameborder
frameBorder
for
htmlFor
maxlength
maxLength
심지어 속성과 프로퍼티는 값이 다를수도 있다. 아래 코드를 실행한 결과는 속성과 프로퍼티의 값이 꼭 같은 것은 아니라는 것을 보여준다.
<a id="target" href="./demo1.html">ot</a>
<script>
//현재 웹페이지가 http://localhost/webjs/Element/attribute_api/demo3.html 일 때
let target = document.getElementById('target');
// http://localhost/webjs/Element/attribute_api/demo1.html
console.log('target.href', target.href);
// ./demo1.html
console.log('target.getAttribute("href")', target.getAttribute("href"));
</script>
Last updated
Was this helpful?