JavaScript #2

haechi·2021년 7월 28일
0

Web

목록 보기
3/69

210728
JavaScript #2


  • HTML코드와 HTML element를 JavaScript롤 접근하는 방법

-JavaScript는 HTML과 연결되어 있어서 내용을 읽어올 수 있다.

또한 HTML을 바꾸거나 추가할 수 있다.

-app.js

document.title = "Good Bye :)"



이처럼 JavaScript에서 HTML을 가져오는 것이다.

-태그의 id로 접근
HTML의 h1태그에 id="title"로 두고 JavaScript에서 document.getElementById("title")을 한다면

위와 같이 id가 title인 h1태그를 가져올 수 있다.

title.innerText = "Got you!"

혹은 내용 변경
-index.html

<!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 autofocus class="hello" id="title">Grab me!</h1>
  <script src="app.js"></script>
</body>
</html>

-변경된 내용

-class name으로 접근하는 방법

const hellos = document.getElementsByClassName("hello")

-TagName으로 접근하는 방법

const title = document.getElementsByTagName("h1")

-querySelector, querySelectorAll
element를 CSS 방식으로 검색할 수 있다.

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

console.log(title)


querySelector에서 .hello -> class name이고 그안의 h1이라는 의미
단 하나의 element를 반환한다.

만약 이처럼 여러개의 div내에 hello가 있고 모두를 가져오고 싶다면
querySelectorAll을 사용하면 된다.

  <div class="hello">
    <h1>Grab me1!</h1>
  </div>
  <div class="hello">
    <h1>Grab me2!</h1>
  </div>
  <div class="hello">
    <h1>Grab me3!</h1>
  </div>
const title = document.querySelectorAll(".hello h1")

console.log(title)

-> id를 통해서 찾고싶다 하면 #hello를 전달하면 원하는 결과를 얻을 수 있다.

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

둘은 같은 의미다 하지만 하위요소를 가져오기에는 querySelector가 적합하다.

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

title.innerText = "Hello~~!~!~!~!~"

이와 같은 방식으로 HTML에서 항목들에 접근할 수 있다.

참고

profile
공부중인 것들 기록

0개의 댓글