웹브라우저 자바스크립트 - 식별자 API
식별자 API - https://opentutorials.org/course/1375/6682
HTML에서 엘리먼트의 이름, id, class는 식별자로 사용되는데
식별자 API는 이 식별자를 가져오고 변경하는 역할을 한다.
Element.tagName
tagName은 변경할 수 없으며 읽기전용이다.
<!DOCTYPE html>
<html>
<body>
<ul>
<li>html</li>
<li>css</li>
<li id="active" class="important current">JavaScript</li>
</ul>
<script>
console.log(document.getElementById('active').tagName) //document.getElementById('active')은 HTMLLIElement객체를 갖게된다, Element객체에 상속되어 지는데 Element객체에는 tagName이라는 프로퍼티를 가지고 있다. 그래서 이 프로퍼티를 사용할 수 있다.
</script>
</body>
</html>
[결과화면]
Element.id
문서에서 단 한번만 등장하는 식별자이다.
<!DOCTYPE html>
<html>
<body>
<ul>
<li>html</li>
<li>css</li>
<li id="active">JavaScript</li>
</ul>
<script>
var active = document.getElementById('active');
console.log(active.id); //active
active.id = 'deactive'; //id값을 변경
console.log(active.id); //deactive
</script>
</body>
</html>
[결과화면]
Element.className
<!DOCTYPE html>
<html>
<body>
<ul>
<li>html</li>
<li>css</li>
<li id="active">JavaScript</li>
</ul>
<script>
var active = document.getElementById('active');
// class 값을 변경할 때는 프로퍼티의 이름으로 className을 사용한다.
active.className = "important current";
console.log(active.className);
// 클래스를 추가할 때는 아래와 같이 문자열의 더한다.
active.className += " readed"
</script>
</body>
</html>
Element.classList
예제를 실행 후 콘솔에서 확인하기
<!DOCTYPE html>
<html>
<body>
<ul>
<li>html</li>
<li>css</li>
<li id="active" class="important current">JavaScript</li>
</ul>
</body>
</html>
[콘솔창]
var active = document.getElementById('active'); //id가 active인 엘리먼트를 active변수에 담는다
active.classList[0]; // classList는 유사배열이기 때문에 배열형태로 사용할 수 있다.
-> "important"
active.classList.add('aabb'); //id값에 aabb를 추가하면 class="important current aabb"가된다.
active.classList.remove('aabb'); // remove를 사용하여 aabb를 삭제하면 class="important current"가 된다.
active.classList.toggle('aabb'); //toggle을 사용하면 aabb값이 없으면 추가해주고 aabb값이 있으면 삭제된다.