사용된 HTML

<!DOCTYPE html>
<html lang="ko">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <script defer src="main.js"></script>
    <link rel="stylesheet" href="main.css" />
    <title>JS practice</title>
  </head>
  <body>
    <button id="id_button">ID</button>
    <button class="class-button">CLASS</button>
    <button class="class-button">CLASS2</button>
    <button class="class-button">CLASS3</button>
  </body>
</html>

1. id 속성 이용하기

id에 해당하는 태그 하나만 지정함

사용법: document.getElementById(아이디이름: string): return HTML

const helloBtnById = document.getElementById("id_button");
console.log(helloBtnById); //HTML의 id태그 출력

출력값

잘 보이도록 CSS도 추가했습니다. 

 

2. class 속성 이용하기

같은 이름의 class 속성이 포함된 모든 값

사용법: document.getElementByClassName(클래스이름:string) : class에 해당하는 태그 모음(HTMLCollection)

const helloButton = document.getElementsByClassName("class-button");

console.log(helloButton);

출력값

3. HTML태그 이름으로 가져오기

사실상 자주 이용 되지 않는다.

사용법: document.getElementByTagName(태그이름: string): tag에 해당하는 태그 모음(HTMLCollection)

 

4.css선택자로 태그 선택하기

//main.css
#id_button {
  color: red;
}

button.class-button {
  color: blue;
}

4.1 하나만 선택하기

사용법: document.querySelector(css: string):css선택자 해당하는 태그 중 가장 첫 번째 태그 하나

4.2 모두 선택하기

사용법: document.querySelector(css: string):css선택자에 해당하는 태그 모음(NodeList)

const helloButton2 = document.querySelector(".class-button");
const helloButtons = document.querySelectorAll(".class-button");

console.log(helloButton2);
console.log(helloButtons);

출력값:

마무리

const helloBtnById = document.getElementById("id_button");
const helloButton = document.getElementsByClassName("class-button");
const helloButton2 = document.querySelector(".class-button");
const helloButtons = document.querySelectorAll(".class-button");

console.log(helloBtnById);
console.log(helloButton);
console.log(helloButton2);
console.log(helloButtons);

자바스크립트에서 HTML의 속성을 이용해서 태그에 접근하는 방법을 알아보았다. 이전에 했던것이지만 리액트를 쓰고 난 후 많이 까먹은 것 같아 다시 적어본다.

'JS' 카테고리의 다른 글

[JS] 이벤트 처리하기  (0) 2023.04.21
[JS] 요소 다루기 정리  (0) 2023.04.21
[JS]모듈(Module) 모듈화(Modularization)/ Import/Export  (0) 2023.04.06
[JS] 다양한 배열 메소드  (0) 2023.04.06
[JS] 에러 객체와 try catch문  (0) 2023.04.05

+ Recent posts