JavaScript에서 HTML DOM Element의 속성 값을 조회,변경하는 방법에 대해서 알아보자.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<h1 id="main-title"> DOM (Document Object Model)</h1>
<ul class="fruit-list">
<li class="fruit">apple</li>
<li class="fruit">banana</li>
<li class="fruit">melon</li>
</ul>
</body>
</html>
|
cs |
위와 같은 HTML 코드가 있을때
fruit 클래스의 포함된 리스트 중 banana를 선택하고 Atrribute를 조회,변경,추가,삭제를 해보자.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
<script>
var fruit = document.querySelectorAll('.fruit');
console.log(fruit);
var banana = fruit[1]
console.log(banana.getAttribute('class')); // class 속성 조회
banana.setAttribute('class','rotten_fruit'); // class 속성 변경
console.log(banana.getAttribute('class')); // 변경된 class 속성 조회
banana.classList.add('fresh'); // class 추가 !
console.log(banana.getAttribute('class')); // 추가된 속성 조회
banana.classList.remove('fresh'); // class 제거 !
console.log(banana.getAttribute('class')); // 제거된 속성 조회
</script>
|
cs |
getAttribute('속성 key')
setAttribute('속성 key','변경할 값')
으로 element의 attribute를 조회, 변경할 수 있다.
그리고 class 같은 경우 특별하게 classList를 통해 add,remove를 할 수 있다.
html에서 하나의 element는 여러개의 class에 속할 수 있다. 따라서 class attribute 같은 경우에는 classList를 통해 관리하는 것이 유용할것으로 생각된다.(css 관련해서 많이 쓰일 것으로 예상된다.)
# Reference : 1분코딩 자바스크립트 기초 Part 3
'HTML5 > JavaScript' 카테고리의 다른 글
이벤트 위임 그리고 this, e.currentTarget, e.target (0) | 2020.11.19 |
---|---|
선택자는 QuerySeletor, QuerySeletorAll를 사용하자 (0) | 2020.11.08 |