여러 개의
querySelectorAll()로 모든 li 요소를 선택한 뒤, forEach()와 classList.add()를 함께 사용하면 됩니다. 반복 과정에서 인덱스 값을 기준으로 조건을 걸어, 원하는 요소에만 특정 클래스를 적용할 수 있습니다.예제
다음은 전체 코드입니다.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<link rel="stylesheet"
href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<style>
.demo1 {
color: yellow;
}
.demo2 {
color: skyblue;
}
</style>
<body>
<ul>
<li>Javascript</li>
<li>MySQL</li>
<li>Java</li>
<li>MongoDB</li>
</ul>
</body>
<script>
addingClassUsingJavascript();
function addingClassUsingJavascript() {
const all = document.querySelectorAll('li');
all.forEach(function (t, i) {
if (i === 1) {
t.classList.add('demo1');
} else if (i === 2) {
t.classList.add('demo2');
}
});
}
</script>
</html>위 프로그램을 실행하려면 파일을 anyName.html(또는 index.html)로 저장한 후, VS Code 편집기에서 해당 파일을 마우스 오른쪽 버튼으로 클릭하고 “Open with Live Server” 옵션을 선택하면 됩니다.
출력 결과
위 코드를 실행하면 다음과 같은 결과가 화면에 표시됩니다.
