쫑가 과정

html과 JavaScript 연결하기, 선택자 본문

JavaScript/공부

html과 JavaScript 연결하기, 선택자

쫑가 2021. 7. 16. 15:32

Document 살펴보기

document가 모든 것들의 시작점이고 web site를 의미한다.

browser는 Html로 이루어져 있는데 JavaScript를 이용해 Html을 불러올 수 있다.

console.log(document);

console에 document를 입력하면 내가 Html을 볼 수가 있다.

이건 javaScript로 Html을 불러올 수 있다는 것이다.

console.dir(document);

그저 object일 뿐인 항목들이 많이 나온다.

그중에 title: 이라고 적힌 부분을 보자.

title항목은 JavaScript에서 title을 정의한 적이 없고 HTML에서 정의한 항목인데 불러올 수가 있다.

Html을 JavaScript의 관점으로 보여준 건데. 이것이 object로 보인다.

document.object

console.log(document.title);

Html에서 <title> 태그에 적혀있는 것이 출력된다.

 

JavaScript는 HTML에 접근하고 읽을 수 있게 설정이 되어있어서

HTML 항목을 JavaScript에 사용할 수 있다.

 

만약 properties 값을 변경한다면 어떨까?

document.title = "goood"
console.log(document.title);

console을 확인해보면 title이 변경된 것을 볼 수 있다.

JavaScript를 통해 HTML이 변경된 거다.

HTML과 JavaScript를 연결하기 위해서 아무것도 하지 않아도 된다.

JavaScript에서 HTML의 항목들을 읽어올 수 있다는 것

JavaSc를 이용해 HTML에 항목들을 추가할 수도 있다는 것이다.

HTML에서 특정항목 선택해 가져오기

여러 object들을 살펴보자.

 

Document - Web API | MDN

Document 인터페이스는 브라우저가 불러온 웹 페이지를 나타내며, 페이지 콘텐츠(DOM 트리)의 진입점 역할을 수행합니다.

developer.mozilla.org

<body>
    <h1 id="title">interesting!</h1>
    <script src="app.js"></script>
</body>

document.getElementById("")는 주어진 ID를 가진 요소의 참조를 반환한다.

const title = document.getElementById("title");
console.dir(title);

html에 h1태그 id="title"을 만들고

JavaScript에서 console.dir(title)을 해보면 title object들을 또 볼 수 있다.

살펴보면 이용하기 좋은 항목들이 많다.

autofocus: false 부분을 보자.

가지고 온 후 수정하기

document에서 항목들을 가지고 오는 것

document항목들을 변경하는 것.

어떤 html element이던 가져올 수 있고 변경할 수 있다.

<body>
    <h1 autofocus id="title">interesting!</h1>
    <script src="app.js"></script>
</body>

<h1 autofocus ~ > 적어주고 다시 보면 autofocus: true로 바뀌어있다.

이렇게 항목들을 보면서 추가해줄 수도 있다.

const title = document.getElementById("title");
title.autofocus = true
title.innerText = "difficult!"
console.dir(title);

물론 javascript에서도 변경하면 브라우저 내에서 변경된다.

getElementBy

Document.getElementsByClassName 주어진 클래스 이름을 갖는 요소의 목록을 반환.

Document.getElementsByTagName() 주어진 태그명을 갖는 요소의 목록을 반환.

Document.getElementsByTagNameNS() 주어진 태그명과 네임스페이스를 갖는 요소의 목록을 반환.

가지고 오는 값이 여러 개면 방식이 달라진다.

<body>
    <h1 class="todo-list">a</h1>
    <h1 class="todo-list">b</h1>
    <h1 class="todo-list">c</h1>
    <h1 class="todo-list">d</h1>
    <h1 class="todo-list">e</h1>
    <script src="app.js"></script>
</body>
const todo = document.getElementsByClassName("todo-list")
console.log(todo)

console을 보면 값이 array로 나온다. 이러면 todo.object형식을 바로 사용할 수 없다.

주로 여러 개를 한 번에 가져올 때 사용한다.

array형식에서 사용하고 싶다면 순서[번호]를 주고 사용하면 된다.

const todo = document.getElementsByClassName("todo-list")
todo[0].innerText = "first!"

querySelectotelement

CSS방식으로 선택자를 검색할 수 있다.

<body>
    <div class="todo-list">
        <h1>a</h1>
        <h1>b</h1>
        <h1>c</h1>
        <h1>d</h1>
        <h1>e</h1>
    </div>
    <script src="app.js"></script>
</body>
const todo = document.querySelector(".todo-list h1");
console.log(todo)

class todo-list안에 있는 h1을 가져온다.

하나의 element를 return 하기 때문에.

여러 개 있으면 첫번째를 가져온다.

그 외 순서들은 nth-child()를 이용한다.

 

:nth-child - CSS: Cascading Style Sheets | MDN

CSS :nth-child() 의사 클래스는 형제 사이에서의 순서에 따라 요소를 선택합니다.

developer.mozilla.org

모두 가져오고 싶으면 querySelectorAll을 사용한다.

const todo = document.querySelectorAll(".todo-list h1");
console.log(todo)

역시 array로 출력된다.

정리

querySelector(".todo)와 getElementByClassName("todo")는 같은 일을 한다.
하지만 querySelector는 하위 요소 가져오는 것이 가능하다.

'JavaScript > 공부' 카테고리의 다른 글

input  (0) 2021.08.20
input 입력값 받기.(input.value)  (0) 2021.07.24
className, DOMTokenList(classList)  (0) 2021.07.21
Event(.addEventListener(), event Handler property)  (0) 2021.07.17
conditional(if,elseif,else)/ 연산자(논리,비교)  (0) 2021.07.14
볼 때마다 헷갈리는 return  (0) 2021.07.12
데이터 정리(array, object, function)  (0) 2021.07.09
Variable  (0) 2021.07.03
Comments