본문 바로가기
Javascript: to do list

08 Elements 엘리먼트와 쿼리셀렉터

by From.h 2023. 5. 30.
728x90
반응형

 

 

엘리먼트 Element의 활용

getElementsByClassTagName & querySelector

 

 

 

 

 

이전 장에서 javascript 를 이용해 classID로 불러오기를 해봤다.

 

이번에는 className으로 불러오기, classTagName으로 불러오기, querySelector로 불러오기를 해보겠다.

 

html은 다음과 같이 title을 className으로 하고, h1 Tag에 감쌌다.

<!DOCTYPE html>
<html lang="en">
<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">
    <link rel="stylesheet" href="style.css">
    <title>Momentum</title>
</head>
<body>
    <h1 class="title">Come on me!</h1>
    <script src="app.js"></script>
</body>
</html>

 

1. getElementsByClassName

 

js파일은 다음과 같이 className을 통해 title을 출력하고 있다.

const title = document.getElementsByClassName("title");

console.log(title);

 

 

결과는 위와 같이 h1이라는 클래스를 가져오고있다.

만약 여러 개의 h1이 있다면 첫 번째 h1 만을 가져온다.

 

 

2. getElementsByTagName

 

보통은 이런 식으로 아래와 같이 tagName을 가져오는 식을 사용한다.

 

 html 파일 body부분

<body>
    <div class="title">
        <h1>Come on me!</h1>
    </div>
    <script src="app.js"></script>
</body>

 

 

js 파일

const title = document.getElementsByTagName("h1");

console.log(title);
 
 

 

html에 class를 title이라 정하고, h1 tag에 문자열을 입력했으며,

js에서 h1 tagName을 통해 element를 불러와 title에 할당하여 출력해서 보여주라고 했다.

그랬더니  [h1] 배열을 보여주고 있다. 아직까지 그 데이터가 배열이라 사용 가능하지 않다.

 

 

 

3. querySelector

이번에는 css 방식으로 element를 검색하는 방법이다.

 

js 파일에 다음과 같이 querySelector를 이용해서 h1 tag안의 문자열을 가져와보자.

const title = document.querySelector(".title h1");

console.log(title);

 

 

 

다만 h1이 여러 개일 경우 그 첫 번째 tag의 내용을 가져오게 되며, 여러 개일 경우 querySelectorAll을 사용하면 모두 가져올 수 있다.

 

또한 getElementById처럼 ID를 활용해서 가져오는 것 또한 가능하다.

 

<!DOCTYPE html>
<html lang="en">
<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">
    <link rel="stylesheet" href="style.css">
    <title>Momentum</title>
</head>
<body>
    <div class="title" id="hello">
        <h1>Come on me!</h1>
    </div>
    <script src="app.js"></script>
</body>
</html>

html에서 class와 id를 정의하고, js에서 다음과 같이 querySelector와 getElementById로 id를 통해 요소를 불러오는 방식이다. 둘 다 같은 의미이다.

const title = document.querySelector("#hello");
const title1 = document.getElementById("hello");

console.log(title,title1);

 

그러므로 결국 모든 요소를 가져올 수 있는 방법으로 querySelector로 가능하기에 이를 주로 사용하게 될 것이다.

 

 

 

 

주의할 점!

getElementBy...으로 불러올 때는 이름만 넣는다

class=title 이 class 가져올 때 getElementsByClassName("class") : 클래스를 

id=title 이 id 가져올 때 getElementById("title") : 아이디를 가져올 때 가져올때 #을 붙인다!

<a> 이 tag를 가져올 때 getElementsByTagName("a") : 태그를 가져올때 아무것도 붙이지 않는다!

quarySelector...으로 불러올 때는 CSS선택자 형식으로 가져와야 함,. or # 등을 붙여서 

 

 

각 메서드별 검색기준! (단수 복수에 주의하자!)

querySelector  : CSS 선택자,. 클래스, #아이디 등이 앞에 붙는 것에 주의, 뒤에 따라서 h1처럼 종속 태그 선택 가능

getElementById : id, 단수임, 문서에 하나만 존재해야 함

getElementsByName : name, 복수임, -모두 찾아줌

getElementsByTagName : 태그 or * , 복수임 -모두 찾아줌

getElementsByClassName : class , 복수임 - 모두 찾아줌

 

 

 

 

 

 

BR. h

 

 

728x90
반응형