본문 바로가기
개발 공부/웹개발

자바스크립트 식별자 API 개념정리(1)_getElementById, className, classList 사용법

by 크롱이크 2021. 5. 10.

식별자 api

엘리먼트를 제어하기 위해서는 그 엘리먼트를 조회하기 위한 식별자가 필요하다. 이번 포스팅은 식별자 api에 대해서 알아보겠습니다.

HTML에서 엘리먼트의 이름과 id 그리고 class는 식별자로 사용됩니다.. 식별자 API는 이 식별자를 가져오고 변경하는 역할을 합니다.

 

1
2
3
4
5
<ul>
<li>html</li>
<li>cdd</li>
<li id="active" class="important current">javascript</li>
</ul>
cs

태그네임을 찾는 방법

Element.id

문서에서 id는 단 하나만 등장할 수 있는 식별자다. 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
 
document.getElementById('active').tagname    //=> "LI"
document.getElementById('active').tagname ="a" //이건 안된다. 왜? 
//이것은 읽기전용이다.


let active = document.getElementById('active');
console.log(active.id);    //===> active
active.id = 'deactive';
console.log(active.id);    //===> deactive
cs

Element.className

클래스는 여러개의 엘리먼트를 그룹핑할 때 사용한다.

1
2
3
4
5
<ul>
<li>html</li>
<li>cdd</li>
<li id="active">javascript</li>
</ul>
cs
1
2
3
4
5
6
7
8
9
10
11
 
이상태에서 
 
let active = document.getElementById('active');
active.className = "importnt current";
 
console.log(active.className);    //===> "importnt current"
active.className += " readed"
 
console.log(active.className);    //===> "importnt current readed"
//여기서 만약 +=를 안붙이고 =만 쓴다면 결과는 ===> " readed" 가 된다. 조심조심
cs

Element.classList

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
 
<ul>
<li>html</li>
<li>cdd</li>
<li id="active" class="marked">javascript</li>
</ul>
 
className에 비해서 훨씬 편리한 사용성을 제공한다.
let active = document.getElementById('active');
console.log(active) = ===> // <li id="active" class="marked">javascript</li>; 
console.log(active.classList)를 치게되면
 
DOMTokenList {0"marked"length1, item: funtion, contains:function,....) 처럼 나온다.
 
여기서
active.classList[0]을 하면 "marked" 가 나온다.
 
추가하는 방법
 
active.classList.add("current")
 
제거하는 방법
 
active.classList.remove("current")
 
스위치처럼 사용하는 방법(넣다뺐다하기위해)
 
active.classList.toggle("current")
 
cs

API 식별자에 대해 알아보았습니다. 생활코딩 자바스크립트 강의에서 더욱 자세히 공부하실수있씁니다.!!

getElementById, className, classList 

반응형

댓글